我想访问在父类构造函数中定义的类变量。这是代码。
class A(object):
def __init__(self):
x = 0
class B(A):
def __init__(self):
super(B, self).__init__()
def func(self):
print self.x
s = B()
s.func()
这给了我错误:
AttributeError: 'B' object has no attribute 'x'
如果我尝试将更func()
改为
def func(self):
print x
然后我得到错误:
NameError: global name 'x' is not defined
如果我尝试将更func()
改为
def func(self):
print A.x
然后我得到了错误
AttributeError: type object 'A' has no attribute 'x'
现在,我的想法不多了。x
在父类中访问该类变量的正确方法是A
什么?谢谢!
注意:我只在项目的“类B”部分上工作,因此我不能真正去修改类A和更改定义变量的方式。那是唯一的约束。
它一定是self.x
,而不仅仅是x
:
class A(object):
def __init__(self):
self.x = 0
只是快速说明-即使从其他方法A
将是x
不可访问:
class A(object):
def __init__(self):
x = 0
def foo(self):
print(self.x) # <- will not work
print(x) # <- will utimately not work
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句