#4.经典类和新式类
#4.1 经典类 :
# class 类名:
# code....
# .....
#4.2 新式类 :
# class 类名(object):
# code...
# code...
# 以后全部用新式类
# 在Python中,所有类默认继承object类,object类是顶级类或者说基类,其他子类叫派生类
#父类
class Father():
def __init__(self):
self.hair = '卷发'
self.address = '湖北'
def print_info(self):
print(f"hair = {self.hair}")
print(f"address = {self.address}")
def __str__(self):
return 'This is Father class'
#父类2(多继承)
class Mother():
def __init__(self):
self.hair = '直发'
self.address = '湖南'
def print_info(self):
print(f"hair = {self.hair}")
print(f"address = {self.address}")
def __str__(self):
return 'This is Mother class'
#子类
class Son(Father, Mother):
def __init__(self):
self.hair = '卷发'
self.address = '广东'
def print_info(self):
print(f"hair = {self.hair}")
print(f"address = {self.address}")
# super(Father, self).__init__()
# super(Father, self).print_info()
# super(Mother, self).__init__()
# super(Mother, self).print_info()
def __str__(self):
return 'This is Son class'
# 子类调用父类的同名属性和方法 : 把父类的同名属性和方法再封装一次
def father_print_info(self):
# #方式一 : 这里一定要先初始化一次父类的同名属性和方法
Father.__init__(self) #这里要传参数 self
Father.print_info(self) #这里要传参数 self
def mother_print_info(self):
Mother.__init__(self)
Mother.print_info(self)
class GrandSon(Son):
def __init__(self):
self.hair = '短发'
self.address = '深圳'
def print_info(self):
print(f"hair = {self.hair}")
print(f"address = {self.address}")
son = Son()
son.print_info()
# son.father_print_info()
# print(son)
#结论 : 如果一个类继承多个父类, 优先继承第一个类的同名属性和方法
# 子类重写了和父类相同的属性或方法时,调用的是子类的属性或方法
#类名.__mro__可以查看该类的继承关系
#print(Son.__mro__)
#输出 (<+class '__main__.Son'>, <class '__main__.Father'>, <class '__main__.Mother'>, <class 'object'>)
#print(type(Son.__mro__))#输出 <class 'tuple'>