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 type
s 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会检查类型,但是会拒绝子类的示例对象)。
- python -- type/isinstance
- python isinstance type区别
- 简述Python isinstance 和type
- python中的type()和isinstance()
- python type、isinstance和metaclass的应用
- [python]type和isinstance的比较
- python简单之isinstance,type使用
- Python 类型比较: type 和 isinstance
- python——type isinstance dir
- Python类型判断type与isinstance
- Python中isinstance和type进行对比
- Python isinstance 和 type,类型判断
- Python中isinstance() 与 type() 区别
- 飘逸的python - 类型判断type与isinstance的区别
- Python学习 Day 8 继承 多态 Type isinstance dir __slots__
- python特殊函数(id, dir, type, isinstance, issubclass, is)
- python数据类型判断type与isinstance的区别
- Python的type 还是要靠isinstance判断类型
- Eclipse中Build Workspace 优化
- ipv6 全球单播地址,link-local address、site-local address、组播、任意波、EUI-64等地址的理解
- [LeetCode]Evaluate Reverse Polish Notation
- 用VS2010建立空白解决方案
- struts2中的constant配置详解
- python -- type/isinstance
- leetcode_Design and implement a data structure for Least Recently Used (LRU) cache
- RTSP协议介绍
- 破解android 程序的基本步骤
- C++ STL 容器技术 之 list双向链表容器
- iOS 去掉tabaar上面的 一条线
- MYSQL日期函数大全
- 关于分库分表(Mysql篇)
- 百度网盘之android4.2源码下载