Python 对象继承与多态

子类(派生类)对象继承父类(基类)对象的属性与方法

对象继承
动物
波斯猫
巴厘猫
沙皮狗
斑点狗

平级子类的方法不能互通。

class Animal():
	def eat(self):
		print('--吃--')
	def drink(self):
		print('--喝--')
	def sleep(self):
		print('--睡--')
	def run(self):
		print('--跑--')

class Dog(Animal):
    def bark(self):
        print('--汪汪--')

class Cat(Animal):
    def catch(self):
        print('--抓老鼠--')

class Cat_Tom(Cat):
	def catch(self):
		print('--Tom永远抓不到杰瑞--')
			#重写覆盖Cat的catch方法		
		super().catch()
			#调用被重写的父类的方法

tom = Cat_Tom()
tom.catch()		#tom有父类Cat的方法(被重写)
tom.sleep()		#tom有父类的父类Animal的方法
>>>
--Tom永远抓不到杰瑞--
--抓老鼠--
----
私有方法、属性在继承中的表现

父类也有小秘密,私有的方法、属性不会被继承,除非通过公有方法转接。

class A:
	def __init__(self):
		self.num1 = 100
		self.__num2 = 200

	def test1(self):
		print('--test1--')

	def __test2(self):
		print('--secret--')

	def test3(self):
		self.__test2()
		print(self.__num2)

class B(A):
	pass

b = B()
b.test1()
print(b.num1)
	'''
	#报错
	b.__test2()
	print(b.__num2)
	'''
b.test3()
>>>
--test1--
100
--secret--
200
多继承

继承多个父类对象

class Base:
        def test(self):
                print('----Base')

class A(Base):
        def test1(self):
                print('----test1')

class B(Base):
        def test2(self):
                print('----test2')

class C(A,B):		#写上多个父类
        pass

c = C()
c.test1()
c.test2()
c.test()
>>>
----test1
----test2
----Base
同名方法调用顺序
  • 尽可能保证所有类的方法不重名,若重名则优先子类方法
调用同名方法
父类方法
子类方法
默认调用
子类
c = C()
print(C.__mro__)

返回方法搜索顺序:

>>>
(<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class '__main__.Base'>, <class 'object'>)

对象同名方法的多态调用,针对引用的对象的方法调用。

调用同名方法
父类方法
子类方法
默认调用
子类
多态调用方法
父类方法
子类方法
自定义函数
父类
子类
class Dog:
        def print_self(self):
                print('大家好')

class Xiaotq(Dog):
        def print_self(self):
                print('Hello everybody')

def introduce(temp):		#temp变量类型未定,由引用变量决定。
        temp.print_self()

dog1 = Dog()
dog2 = Xiaotq()

introduce(dog1)
introduce(dog2)

>>>
大家好
Hello everybody
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值