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
15

>>>b.name
AttributeError: 'B' object has no attribute 'name'

由于B没有调用A的构造函数,因此,实例b上面也没有属性name,造成访问出错。

猜你喜欢

转载自www.cnblogs.com/chaoguo1234/p/9351951.html