python中类型与对象的实例关系?

The instance relation between type and object in python?

显示class类型和对象之间的关系:

issubclass(type,object)
True
issubclass(object,type)
False

很明显type派生自object,objecttype的父亲class,type是儿子classobject

isinstance(type,object)
True
isinstance(object,type)
True

如何理解typeobject的实例,反之亦然?

有用的定义

isinstance(object, classinfo)

Return True if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof.
https://docs.python.org/3.9/library/functions.html?highlight=isinstance#isinstance

1) typeobject

的实例
  • 所有数据都由对象表示,object 是所有 类
  • 的基础

Objects are Python’s abstraction for data. All data in a Python program is represented by objects or by relations between objects.
https://docs.python.org/3.9/reference/datamodel.html#types

object is a base for all classes.
https://docs.python.org/3.9/library/functions.html?highlight=object#object

2) objecttype

的实例
  • object 是类型对象。换句话说,object 是类型,type

Type Objects
Type objects represent the various object types. An object’s type is accessed by the built-in function type()
https://docs.python.org/3.9/library/stdtypes.html?highlight=subclass#type-objects

  • type(object) # returns type

  • type(type) # returns type

  • object.__class__ # returns type

  • type.__class__ # returns type

  • 这有助于我们理解 isInstance(object, type) 将如何 return True.

  • 一种直观的思考方式是 object 对象的类型是 typeobject不是 type 的子类,因为它不继承自 type