什么是python的构造函数

814次阅读
没有评论

什么是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,造成访问出错。

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2019-10-22发表,共计429字。
新手QQ群:570568346,欢迎进群讨论 Python51学习
评论(没有评论)