Python Polymorphism

Polymorphism generalizes a functionality so it can work on different types. It’s an important concept in object-oriented programming.

We can define the same method on different classes:

class Dog:
    def eat():
        print('Eating dog food')

class Cat:
    def eat():
        print('Eating cat food')

Then we can generate objects and we can call the eat() method regardless of the class the object belongs to, and we’ll get different results:

animal1 = Dog()
animal2 = Cat()

animal1.eat()
animal2.eat()

We built a generalized interface and we now do not need to know that an animal is a Cat or a Dog.


This content originally appeared on flaviocopes.com and was authored by flaviocopes.com

Polymorphism generalizes a functionality so it can work on different types. It’s an important concept in object-oriented programming.

We can define the same method on different classes:

class Dog:
    def eat():
        print('Eating dog food')

class Cat:
    def eat():
        print('Eating cat food')

Then we can generate objects and we can call the eat() method regardless of the class the object belongs to, and we’ll get different results:

animal1 = Dog()
animal2 = Cat()

animal1.eat()
animal2.eat()

We built a generalized interface and we now do not need to know that an animal is a Cat or a Dog.


This content originally appeared on flaviocopes.com and was authored by flaviocopes.com


Print Share Comment Cite Upload Translate Updates
APA

flaviocopes.com | Sciencx (2021-02-20T05:00:00+00:00) Python Polymorphism. Retrieved from https://www.scien.cx/2021/02/20/python-polymorphism/

MLA
" » Python Polymorphism." flaviocopes.com | Sciencx - Saturday February 20, 2021, https://www.scien.cx/2021/02/20/python-polymorphism/
HARVARD
flaviocopes.com | Sciencx Saturday February 20, 2021 » Python Polymorphism., viewed ,<https://www.scien.cx/2021/02/20/python-polymorphism/>
VANCOUVER
flaviocopes.com | Sciencx - » Python Polymorphism. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/02/20/python-polymorphism/
CHICAGO
" » Python Polymorphism." flaviocopes.com | Sciencx - Accessed . https://www.scien.cx/2021/02/20/python-polymorphism/
IEEE
" » Python Polymorphism." flaviocopes.com | Sciencx [Online]. Available: https://www.scien.cx/2021/02/20/python-polymorphism/. [Accessed: ]
rf:citation
» Python Polymorphism | flaviocopes.com | Sciencx | https://www.scien.cx/2021/02/20/python-polymorphism/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.