python 中進行面向對象編程,當在資歷的實例調用父類的屬性時,
由於子類的__init__方法重寫了父類的__init__方法,
如果在子類中這些屬性未經過初始化,使用時就會出錯
# !/usr/bin/env python
# -*- coding: utf-8 -*-
class A(object):
def __init__(self):
self.a = 5
def function_a(self):
print('I am from A, my value is %d' % self.a)
class B(A):
def __init__(self):
self.b = 10
def function_b(self):
print('I am from B, my value is %d' % self.b)
self.function_a() # 調用類A的方法,出錯
if __name__ == '__main__':
b = B()
b.function_b()
C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/wxpython/t6.py
I am from B, my value is 10
Traceback (most recent call last):
File "C:/Users/TLCB/PycharmProjects/untitled/wxpython/t6.py", line 22, in <module>
b.function_b()
File "C:/Users/TLCB/PycharmProjects/untitled/wxpython/t6.py", line 17, in function_b
self.function_a() # 調用類A的方法,出錯
File "C:/Users/TLCB/PycharmProjects/untitled/wxpython/t6.py", line 8, in function_a
print('I am from A, my value is %d' % self.a)
AttributeError: 'B' object has no attribute 'a'
Process finished with exit code 1