Object oriented Chapter VII (7): polymorphism and polymorphism, duck type

Polymorphism refers to the failure of a variety of forms (a subclass of abstract class) category. For example, animals have a variety of forms: human, pig, dog

Polymorphism: polymorphism dynamic binding (used in the context of inheritance, polymorphism sometimes called)

Polymorphism is, without considering the specific example of the type used as examples. Polymorphism is divided into static polymorphism and dynamic polymorphism .

Static polymorphism: Any type can be used, such as operator '+' is operated. Can be added to the string, number may be added, listing can be summed

Dynamic polymorphism: refers to invoke a method of abstract class subclass. In the following example:

import abc

class Animal(metaclass=abc.ABCMeta):  # 定义Animal成抽象类
    
    @abc.abstractmethod
    def run(self):
        pass

    @abc.abstractmethod
    def eat(self):
        pass

class People(Animal):
    def run(self):  
        print('people run')

    def eat(self):
        print('people eat')
        
class Dog(Animal):
    def run(self):
        print('dog run')

    def eat(self):
        print('dog eat')
        
p1 = People()
d1 = Dog()

def func(animal):  # 作为多态的接口,用户使用的时候只要调用这个接口就行
    animal.run()

func(p1)  # 使用接口
func(d1)

Polymorphism benefits:

  • Increasing the program's flexibility: no matter how changes in the object, the user is the same kind of form to call. The func (animal)
  • Increasing the scalability of the program:

Ducks type of duck typing

Duck type (is a programming idea): the common heritage without a parent class between classes, as long as they can do the same as the benefits: even a different class, as long as similar, you can use the same interface to call .

python advocating duck type, that is, if it looks like, sounds like, walks like a duck, then he is a duck. python program ape usually write programs based on this behavior. That is, even when not writing class inheritance, also in the same way to define his method

E.g:

class Disk:
    def read(self):
        print('disk read')
    
    def write(self):
        print('disk write')

class Text:
    def read(self):
        print('text read')
    
    def write(self):
        print('text write')

# Disk和Text没有继承关系,但是写法类似。

d1 = Disk()
t1 = Text()

d1.read()  # 有相同的方法
t1.read()  # 有相同的方法

In fact, python built-in class is to do so. For example: list, tuple, str

l = list([1,2,3])
t = tuple(('a','b'))
s = str('hello')

l.__len__()  # 不同的类都有len()方法
t.__len__()
s.__len__()

# 正常情况下需要自己定义接口才能统一调用类的属性
# def len(obj):
#     return obj.__len__()

# 但是实际上python已经做好了这部分,没有上面的接口函数的定义,也可以直接调用。
len(l)
len(t)
len(s)

Guess you like

Origin www.cnblogs.com/py-xiaoqiang/p/11210444.html