Python的object和type理解及主要对象层次结构

一、Object与Type

1、摘自Python Documentation 3.5.2的解释

Objects are Python’s abstraction for data. All data in a Python program is represented by objects or by relations between objects. (In a sense, and in conformance to Von Neumann’s model of a “stored program computer,” code is also represented by objects.)

对象是Python对数据的抽象。Python程序中的所有数据都由对象或对象之间的关系表示。(在某种意义上,并且符合冯·诺依曼的“存储程序计算机”的模型,代码也由对象表示的)。

Every object has an identity, a type and a value. An object’s identity never changes once it has been created; you may think of it as the object’s address in memory. The ‘is‘ operator compares the identity of two objects; the id() function returns an integer representing its identity.

每个对象都有一个标识,一个类型和一个值。对象的身份一旦创建就不会改变; 你可以把它看作内存中的对象地址。is运算符比较两个对象的标识; id()函数返回一个表示其身份的整数。

An object’s type determines the operations that the object supports (e.g., “does it have a length?”) and also defines the possible values for objects of that type. The type() function returns an object’s type (which is an object itself). Like its identity, an object’s type is also unchangeable.

对象的类型决定对象支持的操作(例如,“它有长度吗?”),并且还定义该类型对象的可能值。type()函数返回一个对象的类型(它是一个对象本身)。与它的身份一样,对象的类型也是不可改变的。

2、Pyhtml的解释:

object:

class object
      The most base type

type:

class type(object)
      type(object_or_name, bases, dict)
      type(object) -> the object's type
      type(name, bases, dict) -> a new type

从上图可以看出,对象obeject是最基本的类型type,它是一个整体性的对数据的抽象概念。相对于对象object而言,类型type是一个稍微具体的抽象概念,说它具体,是因为它已经有从对象object细化出更具体抽象概念的因子,这就是为什么type(int)、type(float)、type(str)、type(list)、type(tuple)、type(set)等等的类型都是type,这也是为什么instance(type, object)和instance(object, type)都为True的原因,即类型type是作为object、int、float等类型的整体概念而言的。那么,为什么issubclass(type, object)为True,而issubclass(object, type)为Flase呢?从第二张图,即从继承关系可以看到,type是object的子类,因此前者为True,后者为False。从Python语言的整体设计来看,是先有对象,后有具体的类型,即对象产生类型,类型从属于对象,两者是相互依存的关系。所以:

  • object是Python对数据的抽象,它是Python程序对数据的集中体现。
  • 每个对象都有一个标识,一个类型和一个值。
  • 对象的类型决定对象支持的操作。
  • 某些对象的值可以更改。 其值可以改变的对象称为可变对象;对象的值在创建后不可更改的对象称为不可变对象。

二、对象层次结构

原文地址:https://www.cnblogs.com/yl153/p/6189455.html