有很多不同的范围变量可以绑定到,这是你似乎很困惑。这里有几个:
# a.py
a = 1 # (1) is module scope
class A:
a = 2 # (2) is class scope
def __init__(self, a=3): # (3) is function scope
self.a = a # (4) self.a is object scope
def same_as_class(self):
return self.a == A.a # compare object- and class-scope variables
def same_as_module(self):
return self.a == a # compare object- and module-scope variables
现在看看如何将这些不同的变量(我只叫他们都a
,使点,请不要为真正做到这一点)命名,以及它们是如何具有不同的价值:
>>> import a
>>> a.a
1 # module scope (1)
>>> a.A.a
2 # class scope (2)
>>> obj1 = a.A() # note the argument defaults to 3 (3)
>>> obj1.a # and this value is bound to the object-scope variable (4)
3
>>> obj.same_as_class()
False # compare the object and class values (3 != 2)
>>> obj2 = a.A(2) # now create a new object, giving an explicit value for (3)
>>> obj2.same_as_class()
True
报告中,我们还可以更改其中的任何值:
>>> obj1.same_as_module()
False
>>> obj1.a = 1
>>> obj1.same_as_module()
True
对于参考ENCE,你上面的z.py
或许应该是这样的:
import a
n = a.Names()
d.userNames()
d = n.name
print d
因为a.Name
是类,但是你想引用一个对象范围变量。一个对象是一个类的实例:我调用了我的实例n
。现在我有一个对象,我可以在对象范围变量。这相当于戈拉内克的回答。
就我之前的例子而言,您尝试访问obj1.a
而没有obj1
或类似的东西。我不确定如何更清楚地做到这一点,而不必把它变成面向对象和Python类型系统的介绍性文章。
它应该工作,如果你在模块级别(不在函数中)分配它。 –
你确定吗?这应该工作。 – Joe
该代码可以正常工作 - 您确定这是您的实际代码吗? –