关于思考题,子类不能继承父类私有属性,只可透过self._Parent__varname去读取该私有属性的值,或在父类创建方法返回私有属性的值,然后子类调用父类方法去取得该私有属性的值
class Animal():
def __init__(self, sex, height, weight):
self.__sex = sex
self.height = height
self.weight = weight
def say_hello(self):
raise 'say hello not implemented'
def get_sex(self):
print('Achieve sex information for parent method: {}'.format(self.__sex))
class Person(Animal):
def __init__(self,name,age):
super().__init__('M',172,70)
self.name = name
self.age = age
def say_hello(self):
print('Hello, {}, age: {}, weight:{}'.format(self.name, self.age, self.weight))
print('Sex: {}'.format(self._Animal__sex))
john = Person('John',35)
john.say_hello()
john.get_sex()
========================
Hello, John, age: 35, weight:70
Sex: M
Achieve sex information for parent method: M
展开