python-Object-oriented polymorphic

Source: Internet
Author: User

  1. # polymorphism: One interface, multiple implementations
  2. Class Animal:
  3. def __init__ (self,name):
  4. Self.name=name
  5. Def talk (self):
  6. Print ("Animal can Talk")
  7. # Xia Chu obj represents passing in different objects, invoking the same interface name as the object
  8. @staticmethod
  9. def animal_talk (obj):
  10. Obj.talk ()
  11. Class Cat (Animal):
  12. Def talk (self):
  13. Print (' Meow meow ')
  14. Class Dog (Animal):
  15. Def talk (self):
  16. Print (' Wang Wang ')
  17. # need to invoke different object interface methods to behave differently
  18. D=dog ("rhubarb")
  19. D.talk ()
  20. C=cat ("small white")
  21. C.talk ()
  22. # The following initializes a method in the animal parent class, using a function to pass in a different object, invoking the same method through the parent class to implement the interface of the different objects
  23. Animal.animal_talk (c)
  24. Animal.animal_talk (d)
    • Output Result:
      Want Want
      Meow Meow
      Meow Meow
      Want Want

python-Object-oriented polymorphic

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.