#继承
# class Animal:
# 当没有写父类时,默认继承自object 这是所有类都要继承的类
class Animal(object):
def __init__(self, name):
self.name = name
def run(self):
print('小动物喜欢一天到晚跑个不停')
# 继承自另一个类
class Dog(Animal):
pass
d = Dog('二哈')
# 直接拥有父类的属性
print(d.name)
# 也拥有父类的行为
d.run()
class Animal:
def run(self):
print('一天到晚不停的跑')
class Cat(Animal):
def eat(self):
print('猫喜欢吃鱼')
c = Cat()
# 继承的方法
c.run()
# 衍生的发生
c.eat()
# 动态添加属性
c.color = '白色'
print(c.color)
class Animal:
def eat(self):
print('小动物一天到晚吃个不停')
def run(self):
print('小动物一天到晚跑个不停')
#方法的重写语句super函数
class Cat(Animal):
# 完全不合适,覆盖重写
def run(self):
print('俺走的是猫步')
# 父类的方法不够完善,需要添加完善
def eat(self):
# 保留父类方法中的内容
# Animal.eat(self) # 不建议使用
# super(Cat, self).eat()
# 简化方案,推荐使用
super().eat()
print('俺喜欢吃鱼') #在父类的基础之上又有了新的内容
c = Cat()
c.run()
c.eat()
#多重继承
class A:
def eat(self):
print('eat func in class A')
class B:
def eat(self):
print('eat func in class B')
def test(self):
print('test func in class B')
class C(A, B):
def eat(self):
# 不重写方法,或者使用super,都是按照书写的先后顺序
# 默认会使用前面的类的方法
# super().eat()
# 明确指定调用哪个父类的方法
B.eat(self)
c = C()
c.eat()
c.test()
Python继承、重写方法、多重继承

最新推荐文章于 2023-06-27 17:21:48 发布
