I'm new to Python... and coming from a mostly Java background, if that accounts for anything.
I'm trying to understand polymorphism in Python. Maybe the problem is that I'm expecting the concepts I already know to project into Python. But I put together the following test code:
class animal(object): "empty animal class" class dog(animal): "empty dog class" myDog = dog() print myDog.__class__ is animal print myDog.__class__ is dog
From the polymorphism I'm used to (e.g. java's instanceof
), I would expect both of these statements to print true, as an instance of dog is an animal and also is a dog. But my output is:
False True
What am I missing?
polymorphism is an important feature of class definition in Python that is utilised when you have commonly named methods across classes or sub classes. Polymorphism can be carried out through inheritance, with sub classes making use of base class methods or overriding them.
Python3. In Python, Polymorphism is a way of making a function accept objects of different classes if they behave similarly.
Polymorphism allows us to have one interface to perform similar tasks in many different ways. Polymorphism makes the code easy to change, maintain, and extend by increasing flexibility.
Polymorphism is considered one of the important features of Object-Oriented Programming. Polymorphism allows us to perform a single action in different ways. In other words, polymorphism allows you to define one interface and have multiple implementations.
The is
operator in Python checks that the two arguments refer to the same object in memory; it is not like the is
operator in C#.
From the docs:
The operators is and is not test for object identity: x is y is true if and only if x and y are the same object. x is not y yields the inverse truth value.
What you're looking for in this case is isinstance
.
Return true if the object argument is an instance of the classinfo argument, or of a (direct or indirect) subclass thereof.
>>> class animal(object): pass >>> class dog(animal): pass >>> myDog = dog() >>> isinstance(myDog, dog) True >>> isinstance(myDog, animal) True
However, idiomatic Python dictates that you (almost) never do type-checking, but instead rely on duck-typing for polymorphic behavior. There's nothing wrong with using isinstance
to understand inheritance, but it should generally be avoided in "production" code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With