Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does polymorphism work in Python?

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?

like image 931
froadie Avatar asked May 14 '10 16:05

froadie


People also ask

How does Python support polymorphism?

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.

Which is used to implement polymorphism in Python?

Python3. In Python, Polymorphism is a way of making a function accept objects of different classes if they behave similarly.

Why is polymorphism important Python?

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.

How will you use polymorphism in your code?

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.


1 Answers

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.

like image 149
Mark Rushakoff Avatar answered Sep 23 '22 02:09

Mark Rushakoff