Python学习19:python类的继承

本文介绍了Python中的面向对象编程概念,特别是继承和方法重写。通过实例展示了如何创建子类并调用父类方法,以及如何使用super()进行超继承。同时,文章还展示了错误示例,如父类无法调用子类特有的方法,并讨论了方法重写时的注意事项。
摘要由CSDN通过智能技术生成

继承

父类 子类

  1. 继承如何表示?
class 子类名(父类名):
	pass
  1. 子类可以实现自己独有的方法 ==>重写
  2. super() 超继承:使用父类当中的方法、
实例1class 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
"""
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值