Dev*_*per 6 python class nested-class
令人惊讶的是, 在Python中处理类(嵌套等)看起来并不容易!最近我出现了以下问题并花了几个小时(尝试,搜索......)但没有成功.我阅读了大部分SO相关链接,但没有一个指出这里提出的问题!
#------------------------------------
class A:
def __init__(self):
self.a = 'a'
print self.a
class B(A):
def __init__(self):
self.b = 'b'
A.a = 'a_b'
print self.b, A.a
#------------------------------------
class C:
class A:
def __init__(self):
self.a = 'a'
print self.a
class B(A):
def __init__(self):
self.b = 'b'
A.a = 'a_b'
print self.b, A.a
#------------------------------------
#------------------------------------
>>> c1 = A()
a
>>> c1.a
'a'
>>> c2 = B()
b
>>> c2.a, c2.b
('a_b', 'b')
>>> c3 = C()
>>> c4 = c3.A()
a
>>> c4.a
'a'
>>> c5 = c3.B()
b a_b
>>> c5.b
'b'
>>> c5.a
Traceback (most recent call last):
File "", line 1, in
AttributeError: B instance has no attribute 'a'
代码中的问题在哪里?
和
在两种情况下看来,当B(A)初始化A()未初始化.这个问题的解决方案是什么?请注意,A.__init__()在B()内部调用的术语__init__()不起作用!
更新:
class Geometry:
class Curve:
def __init__(self,c=1):
self.c = c #curvature parameter
print 'Curvature %g'%self.c
pass #some codes
class Line(Curve):
def __init__(self):
Geometry.Curve.__init__(self,0) #the key point
pass #some codes
g = Geometry()
C = g.Curve(0.5)
L = g.Line()
这导致:
Curvature 0.5 Curvature 0
我在寻找什么.
方法中执行的代码在该方法的本地范围内运行.如果访问不在此范围内的对象,Python将在全局/模块范围内查找它,而不是在类范围或任何封闭类的范围内!
这意味着:
A.a = 'a_b'
Run Code Online (Sandbox Code Playgroud)
inside C.B.__init__将设置全局A类的class属性,而不是C.A您可能想要的.为此你必须这样做:
C.A.a = 'a_b'
Run Code Online (Sandbox Code Playgroud)
此外,如果在子类中覆盖它们,Python将不会调用父方法.你必须自己做.
范围规则意味着如果要调用__init__父类的方法C.B.__init__,它必须如下所示:
C.A.__init__(self)
Run Code Online (Sandbox Code Playgroud)
而不是这样的:
A.__init__(self)
Run Code Online (Sandbox Code Playgroud)
这可能是你尝试过的.
| 归档时间: |
|
| 查看次数: |
21430 次 |
| 最近记录: |