Pages

Sunday, December 30, 2012

OBJECT.__class__ is CLASS and "isinstance(OBJECT, CLASS)" for polymorphism in python

The "is" operator in Python compares the two values before and after to check if they point to the same object. Whereass the "is instance" checks if the first parameter (object) is an instance of the second parameter(class).
As a result "dog.__class__ is Animal" returns False, "isinstance(dog, Animal)" returns True.
class Animal:
    pass
    
class Dog (Animal):
    pass
    
dog = Dog()

print dog.__class__ is Animal
print isinstance(dog, Animal)
False True

Things to consider

For C# programmer, this is confusing as "is" operator in C# works as "ins instance" of Python.
In python idiom, you are not encouraged to use type-checking, instead use duck typing instead. In short, you just execute if an object can quack or not instead of checking an object is an instance of a duct that quacks.
class Duck(object): 
    def quack(self):
        print "QUACK!!!"

class DonaldDuck(object): 
    def quack(self):
        print "quack!"


def canQuack(duckType):
    duckType.quack()


duck = Duck()
donaldDuck = DonaldDuck()
canQuack(duck)
canQuack(donaldDuck)

References

How does polymorphism work in Python?

No comments:

Post a Comment