面向对象:多态特性

ernestwang 811 0

多态特性

  • 说明:不同的对象,调用相同的方法,有不同的响应。
  • 示例:
    class Animal:
        def run(self):
            print('小动物走道姿势都不一样')
            
    class Dog(Animal):   
        def run(self):
            print('狗喜欢撒欢疯跑')
        
    class Cat(Animal):
        def run(self):
            print('猫喜欢走猫步') 
            
    def func(obj):
        if hasattr(obj, 'run'):
            obj.run()
        else:
            print('类型有误')
    
    func(Dog())
    func(Cat())

抽象基类(了解)

  • 说明:
    • 抽象基类不能实例化(创建对象)
    • 抽象基类是为了统一接口而存在的
    • 继承自抽象类的子类必须实现抽象基类中定义的抽象方法,否则无法进行实例化
  • 使用:
    from abc import ABC, abstractmethod
    
    # 抽象类:用于抽象方法的类,不能进行实例化(创建对象)
    # 可以通过继承同一个抽象类,完成统一接口的作用
    class Animal(ABC):
        # 定义抽象方法
        @abstractmethod
        def run(self):
            pass
        
    # 继承自抽象类的类必须实现抽象类中定义的抽象方法
    # 否侧无法进行实例化,因此可以做到统一接口
    class Dog(Animal):
        def run(self):
            print('狗喜欢疯跑')
            
    class Cat(Animal):
        def run(self):
            print('猫喜欢都猫步') 
            
    # a = Animal()
    d = Dog()
    c = Cat()

对象支持字典操作

  • 说明:通过内置函数__getitem__、__setitem__、__delitem__
  • 使用:
    class Person:
        # 当做字典操作:设置属性时自动触发
        def __setitem__(self, key, value):
            # print(key, value)
            self.__dict__[key] = value
    
        # 当做字典操作:获取属性时自动触发
        def __getitem__(self, item):
            # print(item)
            return self.__dict__.get(item)
    
        # 当做字典操作:删除属性时自动触发
        def __delitem__(self, key):
            # print(key)
            del self.__dict__[key]
            
    p = Person()
    
    p.name = '大花'
    print(p.name)
    
    p['name'] = '二狗'
    print(p['name'])
    del p['name']
    print(p['name'])

支持函数调用

  • 说明:默认对象不能当做函数调用,重写__call__方法后就可以了
  • 使用: class Person: # 当对象当做函数调用时,会自动触发该方法 def __call__(self, *args, **kwargs): print(args) print(kwargs) # return 'xxx' return sum(args) p = Person() ret = p(1, 2, 3, name='dahua', age=18) print(ret) def test(): pass # 判断一个对象是否可以调用 print(callable(p)) print(callable(test)) # 判断是否拥有'call'属性 print(hasattr(p, 'call')) print(hasattr(test, 'call')) # 判断是否是函数 from inspect import isfunction print(isfunction(test)) print(isfunction(p))

标签: 多态

发布评论 0条评论)

还木有评论哦,快来抢沙发吧~

复制成功
微信号: irenyuwang
关注微信公众号,站长免费提供流量增长方案。
我知道了