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

后端 未结 13 1037
南旧
南旧 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-21 08:03

    I think the cool thing about using a dynamic language like Python is you really shouldn't have to check something like that.

    I would just call the required methods on your object and catch an AttributeError. Later on this will allow you to call your methods with other (seemingly unrelated) objects to accomplish different tasks, such as mocking an object for testing.

    I've used this a lot when getting data off the web with urllib2.urlopen() which returns a file like object. This can in turn can be passed to almost any method that reads from a file, because it implements the same read() method as a real file.

    But I'm sure there is a time and place for using isinstance(), otherwise it probably wouldn't be there :)

提交回复
热议问题