Python 访问实例';从另一个模块中的函数得到的方法

Python 访问实例';从另一个模块中的函数得到的方法,python,class,import,module,instance,Python,Class,Import,Module,Instance,诺布问题 我有以下简单的代码: 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() 正如预期的那样,它会显示“bar” 当

诺布问题

我有以下简单的代码:

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()
正如预期的那样,它会显示“bar”

当我将其拆分为两个文件时: 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)
函数操作()无法访问对象“垃圾邮件”:

文件“test_main.py”,第14行,在
行动()
文件“/home/krzysztof/Documents/dev/Python速成班/12/test_module.py”,第3行,正在运行
spam.bar()
NameError:名称“未定义垃圾邮件”

我知道这种访问是可能的,但我找不到关于如何访问的信息。我缺少什么?

您以前可以访问垃圾邮件,因为它是同一文件中的全局变量。您不能直接从其他文件访问全局文件

正确的方法是将
action()
更改为将垃圾邮件作为参数:

def action(spam):
    a = input("Anything>")
    spam.bar()
    print(spam.foo)

然后使用
action(spam)
调用它。

您可以将类的
spam
实例作为参数传递给动作函数。并更改函数的定义

test\u main.py

from test_module import action 
class Test(): 
    def __init__(self): 
        self.foo = "foo" 
    def bar(self): 
        self.foo = "bar" 

spam = Test() 
action(spam)
def action(spam): 
    a = input("Anything>") 
    spam.bar() 
    print(spam.foo)
测试模块.py

from test_module import action 
class Test(): 
    def __init__(self): 
        self.foo = "foo" 
    def bar(self): 
        self.foo = "bar" 

spam = Test() 
action(spam)
def action(spam): 
    a = input("Anything>") 
    spam.bar() 
    print(spam.foo)
你可以用

from test_main import bar
你可以用这种格式

from FOLDER_NAME import FILENAME
from FILENAME import CLASS_NAME FUNCTION_NAME

导入测试模块文件时,将在导入之前运行该文件中的整个代码。因此,测试模块文件中不存在spam变量。
您应该在action函数中使用spam作为参数。

请解释这是如何解决问题的。如果这不是一个错误,它肯定会导致循环导入。