How does polymorphism work in Python?
How does polymorphism work in Python?
--
Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Breezy Bay
--
Chapters
00:00 Question
01:00 Accepted answer (Score 77)
02:17 Answer 2 (Score 42)
02:47 Answer 3 (Score 11)
03:02 Answer 4 (Score 0)
03:37 Thank you
--
Full question
https://stackoverflow.com/questions/2835...
Accepted answer links:
[From the docs]: http://docs.python.org/reference/express...
[isinstance]: http://docs.python.org/release/2.6/libra...
[duck-typing]: http://en.wikipedia.org/wiki/Duck_typing
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #polymorphism
#avk47
ACCEPTED ANSWER
Score 79
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#.
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.
ANSWER 2
Score 43
phimuemue and Mark have answered your question. But this is ALSO an example of polymorphism in Python, but it's not as explicit as your inheritance based example.
class wolf(object):
def bark(self):
print "hooooowll"
class dog(object):
def bark(self):
print "woof"
def barkforme(dogtype):
dogtype.bark()
my_dog = dog()
my_wolf = wolf()
barkforme(my_dog)
barkforme(my_wolf)
ANSWER 3
Score 11
Try isinstance(myDog, dog) resp. isinstance(myDog, animal).
ANSWER 4
Score 0
just nice example how it is possible to use same field of 2 totally different classes. It is more close to template.
class A:
def __init__(self, arg = "3"):
self.f = arg
a = A()
a.f # prints 3
class B:
def __init__(self, arg = "5"):
self.f = arg
b = B()
b.f # prints 5
def modify_if_different(s,t, field):
if s.__dict__[field] != t.__dict__[field]:
t.__dict__[field] = s.__dict__[field]
else:
s.__dict__[field] = None
modify_if_different(a,b,"f")
b.f # prints 3
a.f # prints 3