继承
父类 子类
- 继承如何表示?
class 子类名(父类名):
pass
- 子类可以实现自己独有的方法 ==>重写
- super() 超继承:使用父类当中的方法、
实例1:
class Man:
name = "man"
def __init__(self):
self.name = " "
print(Man.name)
print(Man("csdn").name)
实例2:
class Yifu:
def __init__(self,brand,model,size):
pass
def sell(self,param):
print("market selling")
print("dont sell")
print("if dont sell")
class Girl(Yifu):
def __init__(self):
super().sell("data")
print("girl mood")
print("you shop my cother")
nvzhuang = GirlYiFu()
nvzhuang.sell()
class Phone:
def __init__(self,number):
self.number = number
def call(self,to,recorded = False):
print("{} to {} call phone".format(self.number,to))
if recorded :
self.record()
def record(self):
print("{}recording".format(self.number))
class Smartphone(phone):
def __init__(self,number,brand):
self.number = number
self.brand = brand
def watch_movie(self,name):
print("moving {}".format(name))
class Iphone(Smartphone):
def __init__(self,number):
#重写例子记得注释super()方法
super().__init__(number, '苹果')
self.number = number
self.brand = "苹果"
def face_time(self):
print("{}faceing".format (self.number))
def call(self,to,recorded = False,face = False):
print(" {} 给 {} 打电话。。".format(self.number, to))
if recorded:
self.record()
#重写例子记得注释super()方法
super().call(to,recordede = False)
super().call(to,recorded = False)
if face:
self.face_time()
normal_phone = Phone('1')
print(normal_phone.record())
'''
打印结果:
1 recording
None
'''
normal_phone = Phone('1')
#父类当中不能调用子类方法。
normal_phone.watch_movie("红海行动")
"""
打印结果:报错:
AttributeError: Phone instance has no attribute 'watch_movie'
"""
smart_phone = SmartPhone("2")
print(smart_phone.record())
print(smart_phone.number)
smart_phone.watch_movie('小偷家族')
"""
打印结果:报错
TypeError: __init__() takes exactly 3 arguments (2 given)
"""
# 当子类和父类具有同样的方法或者属性的时候。
# 父类还是用父类的, 子类不再有父类的,而是用自己的。
normal = Phone("1")
smart = SmartPhone(2, '华为')
重写例子2
iphone = Iphone('苹果5')
iphone.call('开始', face=True)
"""
打印结果:
苹果5 给 开始 打电话。。
"""
smart = SmartPhone("123", '华为')
smart.call('阿东', face=True)
"""
打印结果:报错
TypeError
"""