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

后端 未结 13 1039
南旧
南旧 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 07:45

    The most Pythonic way to check the type of an object is... not to check it.

    Since Python encourages Duck Typing, you should just try...except to use the object's methods the way you want to use them. So if your function is looking for a writable file object, don't check that it's a subclass of file, just try to use its .write() method!

    Of course, sometimes these nice abstractions break down and isinstance(obj, cls) is what you need. But use sparingly.

提交回复
热议问题