作业一:自己试验一下菱形问题下的属性查找顺序
非菱形继承:属性查找顺序以mro顺序查找。新试类和经典类相同。
菱形继承:新试类以广度优先查找,经典类以深度优先查找。都以mro原则查找。
作业二:在实现下述代码的基础上,引入
1、引入属性访问控制+property
2、引入继承与派生的概念来减少代码冗余
注意:要满足什么"是"什么的关系,不满足"是"的关系不要去继承
class Cats:
def __init__(self, body_type, hair, environment, food):
self.body_type = body_type
self.hair = hair
self.__environment = environment
self.food = food
@property # 开放接口
def environment(self):
return f"living in {self.__environment}!"
@environment.setter
def environment(self, new_environment):
self.__environment = new_environment
print(f"已将生活环境修改为{new_environment}\n"
f"living in {new_environment}!")
@environment.deleter
def environment(self):
print("Environment can't delete")
def use_skill(self):
print("Roar")
def __like_human(self): # 不想让子类调用
print("little cats like human!")
class Tiger(Cats):
def __init__(self, body_type, hair, environment, food, sleep_time):
Cats.__init__(self, body_type, hair, environment, food) # 继承属性
self.sleep_time = sleep_time # 添加属性
def use_skill(self):
super().use_skill() # 调用继承方法
print("clamp")
java_tiger = Tiger("big", "yellow", "wild", "meat", 15)
print(java_tiger.__dict__) # 查看属性
java_tiger.use_skill() # 继承的属性
print(java_tiger.environment) # 查看接口隐藏属性
java_tiger.environment = "city" # 修改属性
del java_tiger.environment
---------------------------------------------------------
>>> {'body_type': 'big', 'hair': 'yellow', '_Cats__environment': 'wild', 'food': 'meat', 'sleep_time': 15}
>>> Roar
>>> clamp
>>> living in wild!
>>> 已将生活环境修改为city
>>> living in city!
>>> Environment can't delete