可能我來的情況是,從B級稱爲A類的方法下面的程序是如何在python
class A(object):
def __init__(self, a):
self.a = a
def abc(self):
print self.a
class B(A):
def __init__(self):
super(B, self).abc()
def method1():
a = A(2)
method1()
b = B()
Expecting Output: 2
是否有可能從B級不斷變化的調用方法「ABC」類A,並且不應該在類B中創建類A對象。如果是,請讓我知道解決方案。
我試過的上面的程序出錯了。
而且我得到的錯誤是低於
Traceback (most recent call last):
File "a.py", line 12, in <module>
b = B()
File "a.py", line 10, in __init__
super(B, self).abc()
File "a.py", line 6, in abc
print self.a
AttributeError: 'B' object has no attribute 'a'
你期望這個打印,考慮了''未初始化什麼嗎? – Karin
'self.a'在'A'的__init __()'函數中定義。由於您在'B'中覆蓋'__init __()','self.a'沒有在'B'中定義。 – MattDMo
您需要調用'super(A,self).__ init __(...)'以確保所有屬性都設置正確。 – jonrsharpe