class Cat(Animal):
def __init__(self, weight):
# 覆盖了父类的__init__,所以定义实例时不需要指定name和age
self.__weight = weight
self._weight = weight + 1
self.weight = self._weight + 1
def get_myweight(self):
print(
"My weight is"
, self._weight,
"kg"
)
def get_trueweight(self):
print(
"Actually the cat's weight is"
,self.__weight)
@staticmethod
def print_cat():
print(
"这个类是Animal类的子类,也是Blackcat类的父类"
)
print(
"Cat类和Blackcat类结合,主要用于讲解私人属性、方法的继承与覆盖"
)
print(
"weight是普通属性,可以在外部访问,即用类调用属性获得,可以被子类内部调用"
)
print(
"_weight这样前面加一个下划线表示希望你不要在外部访问它,但是还是可以访问的,可以被子类内部调用"
)
print(
"__weight这样加两个下划线的是不允许外部访问的,只可以在类中被调用,不可以被子类内部调用"
)
print(
"__init__在子类中定义则覆盖了父类中的__init__,不需要指定父类中的属性,也无法调用父类的属性"
)
print(
"在子类中实现和父类同名的方法,也会把父类的方法覆盖掉"
)
class Blackcat(Cat):
def get_weight(self):
print(
"My weight is"
, self.weight)
def get_weight_again(self):
# 可以
print(
"Actuall my weight is"
, self._weight)
def get_true_weight(self):
# 这个方法因为无法调用self.__weight所以这个方法无法使用
print(
"My weight is exactly"
, self.__weight)
def get_trueweight(self):
# 覆盖了Cat父类中定义的方法
print(
"My weight is exactly"
, self._weight+1)