问题描述
在 Python ,令人惊讶的中处理类(嵌套等)看起来不容易!以下问题最近出现在我身上,花了几个小时(尝试,搜索...)没有成功。我读了大部分SO相关链接,但没有人指出这里提出的问题!
Dealing with classes (nested etc) does not look easy in Python, surprisingly! The following problem appeared to me recently and took several hours (try, search ...) without success. I read most of SO related links but none of them has pointed the issue presented here!
#------------------------------------
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'
代码中的问题?
AND
在这两种情况下,似乎当B(A)被初始化时,A()没有被初始化。这个问题的解决方案是什么?请注意,在B()的 __ init __()
内调用的 A .__ init __()
Where is the problem in the code?ANDIn both cases it seems that when B(A) is initialized A() is not initialized. What is the solution for this issue? Note that the term A.__init__()
being called inside B()'s __init__()
does not work!
更新:
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将在类范围或任何封闭类的范围内在全局/模块范围中查找 NOT !
The code executed in a method runs in the local scope of that method. If you access an object that is not in this scope, Python will look it up in the global/module scope, NOT in the class scope or the scope of any enclosing class!
这意味着:
A.a = 'a_b'
内部 CB__init __
将设置全局的类属性 A
类,而不是您可能想要的 CA
。为此,您必须这样做:
inside C.B.__init__
will set the class attribute of the global A
class, not C.A
as you probably intended. For that you would have to do this:
C.A.a = 'a_b'
此外,如果在子类中重写它们,Python不会调用父方法。
Also, Python will not call parent methods if you override them in subclasses. You have to do it yourself.
范围规则意味着如果你想调用 __ init __
方法 CB__init __
中的父类,它看起来像这样:
The scoping rules mean that if you wanted to call the __init__
method of the parent class inside C.B.__init__
, it has to look like this:
C.A.__init__(self)
而不是这样:
A.__init__(self)
可能是你尝试过的。
这篇关于Python中的嵌套类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!