python - python中类型与对象的关系

标签 python

我正在通读 this blog ,其中包含:

Since in Python everything is an object, everything is the instance of a class, even classes. Well, type is the class that is instanced to get classes. So remember this: object is the base of every object, type is the class of every type. Sounds puzzling? It is not your fault, don't worry. However, just to strike you with the finishing move, this is what Python is built on.

>>> type(object)
<class 'type'>
>>> type.__bases__
(<class 'object'>,)

我无法理解这一点。任何人都可以用不同的方式解释这种关系以使其更清楚吗?

最佳答案

type(x)的关系和x.__class__的结果基本一样:

for obj in (object,type,1,str):
    assert type(obj) is obj.__class__

print("type(obj) and obj.__class__ gave the same results in all test cases")

__bases__ 表示派生类的基础:

class parent:
    pass

class child(parent,int):
    pass

print(child.__bases__) # prints (<class '__main__.parent'>, <class 'int'>)

但是,如果您询问 objecttype 之间的奇怪关系:

   # are `object` and `type` both instances of the `object` class?
>>> isinstance(object, object) and isinstance(type, object)
True
   # are they also instances of the `type` class?
>>> isinstance(object, type) and isinstance(type, type)
True
   # `type` is a subclass of `object` and not the other way around (this makes sense)
>>> [issubclass(type, object), issubclass(object, type)]
[True, False]

这更像是先有鸡还是先有蛋的问题:哪个先出现?

答案是用C定义的PyObject

objecttype 可用于 python 解释器之前,它们的底层机制是在 C 中定义的,并且实例检查在它们被定义后被覆盖。 (表现得像抽象类,参见 PEP 3119 )

你可以把它看成是这样的 python 实现:

#this wouldn't be available in python
class superTYPE(type):
    def __instancecheck__(cls,inst):
        if inst ==TYPE:
            return True
        else:
            return NotImplemented #for this demo
    
class TYPE(type,metaclass=superTYPE):
    def __instancecheck__(cls,inst):
        if inst in (OBJECT,TYPE):
            return True
        else:
            return NotImplemented #for this demo

class OBJECT(metaclass=TYPE):
    pass

# these all pass
assert isinstance(TYPE,OBJECT)
assert isinstance(OBJECT,TYPE)
assert isinstance(TYPE,TYPE)
assert isinstance(OBJECT,OBJECT)

实际上它可能更好地表示为:

#this isn't available in python
class superTYPE(type):
    def __instancecheck__(cls,inst):
        if inst in (TYPE,OBJECT):
            return True
        else:
            return NotImplemented #for this demo
    
class OBJECT(metaclass=superTYPE):
    pass


class TYPE(OBJECT):
    pass

但是如果您想确切地知道它是如何工作的,您需要查看用 C 编写的源代码。

关于python - python中类型与对象的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36339553/

相关文章:

python - 有没有一种简单的方法可以将 Pandas 系列转换为系列中值的比率交叉表?

python - 是否可以从 Windows 命令提示符运行 python 脚本并同时传递该脚本的参数?

python - 如何获得相对于其他变量的类别总和?

java - 动态规划-最大切割的杆切割问题和实际解决方案

python - 为什么导入 win32ui 后脚本不会退出

基于Python的简单计时器脚本无法正常工作

python - 如何从python中的文件中找到每个工作角色的平均工资

python - 如何使用python获取网页窗口数据?

python - 使用python将mysql中的值分配给dict

python - 如何在Python中计算数值趋势线