后浪云Python教程:什么是python的构造函数
Python中的构造函数是__init__函数。在Python中,子类如果定义了构造函数,而没有调用父类的,那么Python不会自动调用,也就是说父类的构造函数不会执行。
比如有test.py的module文件:
class A: def __init__(self, name): self.name = name class B(A): def __init__(self, age): self.age = age
子类B继承自A,但是子类B的构造函数没有调用A的构造函数。下面我们这样测试:
>>>import test >>>b = test.B(15) >>>b.age >>>b.name AttributeError: 'B' object has no attribute 'name'
由于B没有调用A的构造函数,因此,实例b上面也没有属性name,造成访问出错。
版权声明:
作者:后浪云
链接:https://www.idc.net/help/178694/
文章版权归作者所有,未经允许请勿转载。
THE END