我对 Python 中的类有疑问。 我想知道如何在其他 python 程序中调用在模块中创建的对象。
让我举个例子。我在“class_module.py”文件中有这些对象
def objectCase():
object1 = class_name("object1")
object2 = class_name("object2")
object3 = class_name("object3")
def other_objectCase():
other_object1 = class_name("other_object1")
other_object2 = class_name("other_object2")
other_object3 = class_name("other_object3")
使用 from class_module.py import *
,我想如果我使用 objectCase()
函数,我的程序中有这些对象 (object1, object2 , object3)
并且,如果我使用 otherobjectCase()
函数,我将调用所有 otherobject
。
但是这是错误的。
有什么问题?
最佳答案
您正在函数内部创建局部变量。一旦函数返回,它们就会丢失。如果您以后需要这些对象,将它们返回
给调用者
return object1, object2, object3
并在调用代码中为它们绑定(bind)名称
a, b, c = objectCase()
关于python - 如何调用在模块中创建的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9808516/