我正在尝试访问我在 Python 的另一个模块内的一个函数中创建的变量来绘制图表,但 Python 找不到它们。
我有一些代码,例如:
class1:
def method1
var1 = []
var2 = []
#Do something with var1 and var2
print var1
print var2
return var1,var2
sample = class1()
sample.method1
然后是另一个文件,例如:
from class1 import *
class number2:
sample.method1()
这按预期执行并打印 var1 和 var2,但我无法在类号 2 内调用 var1 或 var2。
正如 Francesco 在他的评论中所说,您发布的代码充满了语法错误。也许你可以粘贴正确的一个。
您不是从类导入,而是从包或模块导入。另外,除非它是 callable,否则你不会“调用”变量。
就你而言,你可以:
file1.py:
class class1:
def __init__(self): # In your class's code, self is the current instance (= this for othe languages, it's always the first parameter.)
self.var = 0
def method1(self):
print(self.var)
sample = class1()
file2.py:
from file1 import class1, sample
class class2(class1):
def method2(self):
self.var += 1
print(self.var)
v = class2() # create an instance of class2 that inherits from class1
v.method1() # calls method inherited from class1 that prints the var instance variable
sample.method1() # same
print(v.var) # You can also access it from outside the class definition.
v.var += 2 # You also can modify it.
print(v.var)
v.method2() # Increment the variable, then print it.
v.method2() # same.
sample.method1() # Print var from sample.
#sample.method2() <--- not possible because sample is an instance of class1 and not of class2
请注意,要在
method1()
中包含 class2
,class2
必须继承自 class1
。但您仍然可以从其他包/模块导入变量。
另请注意,
var
对于该类的每个实例都是唯一的。