python -- type/isinstance

来源:互联网 发布:中国蓝tv网络直播 编辑:程序博客网 时间:2024/04/19 20:09

http://stackoverflow.com/questions/1549801/differences-between-isinstance-and-type-in-python
http://stackoverflow.com/questions/707674/how-to-compare-type-of-an-object-in-python

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

To summarize the contents of other (already good!) answers, isinstance caters for inheritance (an instance of a derived classis an instance of a base class, too), while checking for equality of type does not (it demands identity of types and rejects instances of subtypes, AKA subclasses).

Normally, in Python, you want your code to support inheritance, of course (since inheritance is so handy, it would be bad to stop code using yours from using it!), soisinstance is less bad than checking identity of types because it seamlessly supports inheritance.

It's not that isinstance is good, mind you -- it's just less bad than checking equality of types. The normal, Pythonic, preferred solution is almost invariably "duck typing": try using the argumentas if it was of a certain desired type, do it in a try/except statement catching all exceptions that could arise if the argument was not in fact of that type (or any other type nicely duck-mimicking it;-), and in theexcept clause, try something else (using the argument "as if" it was of some other type).

....

Here's why isinstance is better than type:

class Vehicle:    passclass Truck(Vehicle):    pass

in this case, a truck object is a Vehicle, but you'll get this:

isinstance(Vehicle(), Vehicle)  # returns Truetype(Vehicle()) == Vehicle      # returns Trueisinstance(Truck(), Vehicle)    # returns Truetype(Truck()) == Vehicle        # returns False, and this probably won't be what you want.


大致的意识是:
isinstance 主要是配合继承机制(派生类是基类的一个实例),在检查类型是否相同时,type无法完成相关任务(type会检查类型,但是会拒绝子类的示例对象)。




0 0
原创粉丝点击