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)
No comments:
Post a Comment