我不了解导入和来自导入的工作方式。请看下面的例子。
我在类的文件中有一个类和一个对象,我希望它具有全局范围。
# File alpha.py
class Alpha():
def __init__(self):
self.alpha = 0
def set(self, value):
self.alpha = value
def get(self):
return self.alpha
# This is the global variable
alpha = None
在另一个文件(control.py)中我想访问alpha.py文件中的变量alpha,所以我使用:
# File control.py
from alpha import alpha
def control():
a = alpha.get()
print ('Value of alpha in control ', a)
在main.py中我想创建一个像这样的alpha实例:
# File main.py
from alpha import Alpha, alpha
alpha = Alpha()
alpha.set(1)
a = alpha.get()
print ('Value in main: ', a)
from control import control
control()
结果是(显然alpha的范围是本地的,尽管我使用+ import):
('Value in main ', 1)
Traceback (most recent call last):
File "main.py", line 13, in <module>
main()
File "main.py", line 11, in main
control()
File "control.py", line 4, in control
a = alpha.get()
AttributeError: 'NoneType' object has no attribute 'get'
但是,如果我使用导入的完整对象路径,它可以工作:
# File main2.py using simple import
import alpha
alpha.alpha = alpha.Alpha()
alpha.alpha.set(1)
a = alpha.alpha.get()
print ('Value in main ', a)
from control import control
control()
调用main2.py的结果是:
('Value in main ', 1)
('Value of alpha in control ', 1)
我期待同样的行为。我在这里缺少什么?
感谢您的回答
答案 0 :(得分:0)
[编辑]
这与Python中
local variables
VSmodule members
之间的内存操作差异有关。
修改代码以显示它:
# File alpha.py
class Alpha():
@staticmethod
def getalpha():
global alpha
return alpha
alpha = None
# File control.py
from alpha import alpha
def control():
print("control: ", id(alpha))
在 main.py 中,instance
会新建一个内存但不会修改模块本身。
alpha = Alpha()
,alpha(main.py 中的局部变量)创建为实例Alpha()并为其分配新内存。然后, control.py 导入原始模块。
# File main.py
from alpha import Alpha, alpha
print("main: ", id(alpha), id(Alpha.getalpha())
alpha = Alpha()
print("main: ", id(alpha), id(Alpha.getalpha()))
from control import control
control()
('main: ', 4530210424, 4530210424) <--- initial value, initial value
('main: ', 4532198216, 4530210424) <--- <alpha.Alpha>, initial value
('control: ', 4530210424) <--- get member of original module
另一方面,在 main2.py 中,members of module/class
会更改其成员价值。
alpha.alpha = alpha.Alpha()
,alpha.alpha(main2.py 中的 alpha.py成员)被创建为实例Alpha()并为其分配新内存。然后, control.py 导入修改后的模块。
# File main2.py using simple import
import alpha
print("main2: ", id(alpha.alpha), id(alpha.Alpha.getalpha()))
alpha.alpha = alpha.Alpha()
print("main2: ", id(alpha.alpha), id(alpha.Alpha.getalpha()))
from control import control
control()
('main2: ', 4425401976, 4425401976) <--- initial value, initial value
('main2: ', 4427402056, 4427402056) <--- <alpha.Alpha>, <alpha.Alpha>
('control: ', 4427402056) <--- get member of modified module