Difference between type and object primitive objects

前端 未结 1 1508
伪装坚强ぢ
伪装坚强ぢ 2021-02-06 13:21

From what I understand of Python 3, the type type is the meta-class that is used to create Class objects, so type is to object as \"Car\"

相关标签:
1条回答
  • 2021-02-06 13:38

    Every class of objects in Python inherits the behaviours of the object class. Firstly, it means that

    >>> isinstance(x, object)
    True
    

    will be true in Python 3 no matter what x happens to be bound to. It also means that everything will also inherit the methods of the object as such, unless overridden by a more specific class. Thus, x == y will resort to object.__eq__ if neither of x or y overrode the __eq__ method.

    type in Python 3 is also an object - it inherits from object:

    >>> isinstance(type, object)
    True
    

    It means that type is an object, and it has inherited the behaviour from the object class. That is what enables one to write things like

    >>> type == type
    True
    >>> type.__eq__
    <slot wrapper '__eq__' of 'object' objects>
    

    The type.__eq__ was inherited from the object class.

    But the object class itself is also a type:

    >>> isinstance(object, type)
    True
    

    It means that the class object as an object inherits the behaviour of type - type is object's metaclass.

    And of course type's metaclass is type:

    >>> isinstance(type, type)
    True
    

    And the class object is an object too:

    >>> isinstance(object, object)
    True
    

    When you construct an instance of class, the class itself is responsible for both the meat and bones for that class, but perhaps one could put the distinction in that the bones follows the ordinary class inheritance, and meat is split between the class and the metaclass lineage; and the metaclass is also the bones for the class object itself.

    0 讨论(0)
提交回复
热议问题