duck typing in python

  1. Python does not support polymorphism or use polymorphism. The concept of polymorphism is applied to strongly typed languages ​​such as java and C#, while Python advocates duck typing (Duck Typing)
  2. Duck typing: is a style of dynamic typing. The valid semantics of an object are not determined by inheriting from a specific class or implementing a specific interface, but by the current set of methods and properties. The name of the concept comes from the duck test proposed by James Whitcomb Riley, which can be expressed like this:
    "When you see a bird that walks like a duck, swims like a duck, and quacks like a duck, then the bird It can be called a duck."
  3. In duck typing, the concern is not the object type itself, but how it is used. We can write a function that takes an object of type duck and calls its walk and call methods. In a duck-typed language, such a function could take an object of any type and call its go and call methods. If the methods that need to be called do not exist, a runtime error will be raised.
class F1:
    pass

# 假设,S1是我们的正统类,它继承于根正苗红的F1,是我们的正统类
class S1(F1):
    def show(self):
        print('S1.show')

# S2是路人甲,是个歪瓜裂枣,但是他自己也有一个叫show的方法。
class S2:
    def show(self):
        print('S2.show')


# 在Java或C#中定义函数参数时,必须指定参数的类型,也即是说,我们如果用
# Java写下面的Func,需要告知,obj是F1类还是其他什么东西。
# 如果限定了F1,那么S2是不可以被采纳的。
# 然而,在Python中,一切都是Obj,它不care你到底是什么类,直接塞进去就可以

def Func(obj):
    """Func函数需要接收一个F1类型或者F1子类的类型"""
    obj.show()

s1_obj = S1()
Func(s1_obj) # 在Func函数中传入S1类的对象 s1_obj,执行 S1 的show方法,结果:S1.show

s2_obj = S2()
Func(s2_obj) # 在Func函数中传入Ss类的对象 ss_obj,执行 Ss 的show方法,结果:S2.show

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324628111&siteId=291194637