What's the canonical way to check for type in Python?

后端 未结 13 1032
南旧
南旧 2020-11-21 07:34

What is the best way to check whether a given object is of a given type? How about checking whether the object inherits from a given type?

Let\'s say I have an objec

相关标签:
13条回答
  • 2020-11-21 08:08

    Here is an example why duck typing is evil without knowing when it is dangerous. For instance: Here is the Python code (possibly omitting proper indenting), note that this situation is avoidable by taking care of isinstance and issubclassof functions to make sure that when you really need a duck, you don't get a bomb.

    class Bomb:
        def __init__(self):
            ""
    
        def talk(self):
            self.explode()
    
        def explode(self):
            print "BOOM!, The bomb explodes."
    
    class Duck:
        def __init__(self):
            ""
        def talk(self):
            print "I am a duck, I will not blow up if you ask me to talk."    
    
    class Kid:
        kids_duck = None
    
        def __init__(self):
            print "Kid comes around a corner and asks you for money so he could buy a duck."
    
        def takeDuck(self, duck):
            self.kids_duck = duck
            print "The kid accepts the duck, and happily skips along"
    
        def doYourThing(self):
            print "The kid tries to get the duck to talk"
            self.kids_duck.talk()
    
    myKid = Kid()
    myBomb = Bomb()
    myKid.takeDuck(myBomb)
    myKid.doYourThing()
    
    0 讨论(0)
提交回复
热议问题