Python继承、重写方法、多重继承

Python类与继承
本文介绍Python中类的定义与使用,包括如何创建类、实例化对象、定义方法及属性。同时详细讲解了继承的概念,演示了如何实现单一继承与多重继承,并展示了方法重写和super函数的使用。
#继承
# 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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值