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:Python27python.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