子类不能继承和调用父类中的私有方法

举个例子:

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

    def __play(self):
        print('Animal,__play')

    def play(self):
        print('Animal,play')


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

    def say(self):
        self.play()
        #错误
        self.__play()


dog = Dog()
dog.say()

在say方法之中调用play方法没有任何问题,但是在调用__play方法的时候,会报错:

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

这说明父类中的私有方法不能被子类继承

继承可以一级一级往下继承,就如爷爷->父亲->儿子的关系

你也可能喜欢

发表评论