面向对象-抽象类

抽象类只能被继承,不能实例化。统一标准,规范子类方法。

定义三个动物类,并创建“走”方法

class People:
    def walk(self):
        print('is walking')
class Pig:
    def run(self):
        print('is runing')
class Dog:
    def zou(self):
        print('is zouing')
peo1=People()
pig1=Pig()
dog1=Dog()

使用者访问对象“走”的属性,不同对象的方法不一样,这就导致困惑

peo1.walk()
pig1.run()
dog1.zou()

通过抽象类实现,父类定义方法,不写实现代码,具体实现在子类中实现

#给以下动物创建父类,只定义方法名,不写功能
class Animal(metaclass=abc.ABCMeta):
    #装饰器规定子类必须有该属性
    @abc.abstractmethod
    def run(self):
        pass
    @abc.abstractmethod
    def eat(self):
        pass
class People(Animal):
    #重写父类方法
    def run(self):
        print('pople is walking')
    def eat(self):
        print('pople is eating')
class Pig(Animal):
    def run(self):
        print('pig is walking')
    #无eat方法直接pass即可
    def eat(self):
        pass
class Dog:
    def run(self):
        print('dog is walking')
    def eat(self):
        print('dog is eating')
peo1=People()
pig1=Pig()
dog1=Dog()

再访问对应“走”即可run

#访问对象“走”的属性通过run方法即可,吃的属性eat即可
peo1.run()
pig1.run()
dog1.run()

 

转载于:https://www.cnblogs.com/yaya625202/p/8871701.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值