What type of duck

"If we see a bird walks like a duck, swim like a duck and quacks like a duck, then this bird can be called a duck."

 

  • Focus is on the behavior of the object, rather than the type (duck typing)
  • Such as file, StringIO, socket object supports read / wtite method (file like object).
  • Another example is the definition of a __iter__ magic methods of objects can be used for iteration.

 

for example

 

class Duck:
    def quack(self):
        print("gua gua gua")


class the Person:
     DEF quack (Self):
         Print ( " I'm human, I would GUA, GUA, GUA " )


def in_the_forest(duck):
    duck.quack()



def game():
    donald = Duck()
    john = Person()
    in_the_forest(donald)
    in_the_forest(john)
    print(type(donald))
    print(type(john))
    print(isinstance(donald, Duck))
    print(isinstance(john, Person))


game()

 

 

 

 

Focus is on interfaces and methods which have the object, rather than what type it is.

 

Guess you like

Origin www.cnblogs.com/dairuiquan/p/11444140.html