python在类的继承时,需要注意,当子类定义了构造方法的时候,那么父类的构造方法就不会被自动调用了

举个例子

class Animal:
    def __init__(self, name):
        self.name = name

    def play(self):
        print('我是:', self.name)


class Dog(Animal):
    def __init__(self):
        print('旺财')


dog = Dog()
#错误
dog.play()

如果执行这个例子,那么解释器就会报错:

AttributeError: 'Dog' object has no attribute 'name'

这说明’Animal’类的构造方法没有被执行。我们可以使用super函数调用’Animal’的构造函数。修改之后的代码如下:

class Animal:
    def __init__(self, name):
        self.name = name

    def play(self):
        print('我是:', self.name)


class Dog(Animal):
    def __init__(self):
        super(Dog, self).__init__('旺财')


dog = Dog()
dog.play()

执行结果如下:

我是 旺财

你也可能喜欢

发表评论