【发布时间】:2020-07-16 15:05:36
【问题描述】:
菜鸟问题。
我有以下简单的代码:
class Test():
def __init__(self):
self.foo = "foo"
def bar(self):
self.foo = "bar"
def action():
a = input("Anything>")
spam.bar()
print(spam.foo)
spam = Test()
action()
它按预期显示“条形图”。
当我把它分成两个文件时: test_main.py:
from test_module import action
class Test():
def __init__(self):
self.foo = "foo"
def bar(self):
self.foo = "bar"
spam = Test()
action()
还有 test_module.py:
def action():
a = input("Anything>")
spam.bar()
print(spam.foo)
函数 action() 无法访问对象“垃圾邮件”:
File "test_main.py", line 14, in <module>
action()
File "/home/krzysztof/Documents/dev/Python Crash Course/12/test_module.py", line 3, in action
spam.bar()
NameError: name 'spam is not defined'
我知道这种访问是可能的,但我找不到有关如何进行访问的信息。我错过了什么?
【问题讨论】:
标签: python class import module instance