Objects, values and types

All data in a Python program is represented by objects or by relations between objects.

Every object has an identity, a type and a value.

  • Python 对象创建之后,identity 是不会变的,你可以将它看成该对象在内存中的地址。

  • Python 的 is 操作符比较的就是对象的 identity== 比较的是 value

  • Python 的内置函数 id() 可以获取一个整数,代表了该对象的 identity。CPython 和 IPython id() 获取的是内存的地址。

  • Python 对象的 type 也是不可以改变的,可以用内置函数 type() 获取对象的 type

  • Python 对象根据 value 是否可以改变分为:可变对象(mutable)和不可变对象(immutable)。

  • 常见的 mutable 对象:list, dict, bytearray, set, etc;immutable 对象:int, float, complex, str, tuple, bytes, frozeset, etc。

  • 如果 immutable 对象中包含了 mutable 对象,该 mutable 对象的 value 是可变的。如:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    >>> a = []
    >>> id(a)
    140537664498648
    >>> b = (a, 1)
    >>> b
    ([], 1)
    >>> id(b)
    140537664384752
    >>> a.append(0)
    >>> b
    ([0], 1)
    >>> id(a)
    140537664498648
    >>> id(b)
    140537664384752
  • For immutable types, operations that compute new values may actually return a reference to any existing object with the same type and value, while for mutable objects this is not allowed. 新建的 immutable 对象可能是已经存在 imutable 对象的一个引用,新建的 mutable 对象是一个新的对象。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    >>> a = 'abcde'
    >>> b = 'abcde'
    >>> id(a)
    140537664090832
    >>> id(b)
    140537664090832
    >>> c = []
    >>> d = []
    >>> id(c)
    140537664333368
    >>> id(d)
    140537664498648

    对于 int 类型的 imutable 对象,值在 -5 - 256 之间的时候,新建对象都是引用。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    >>> a = -6
    >>> b = -6
    >>> a is b
    False
    >>> a = -5
    >>> b = -5
    >>> a is b
    True
    >>> a = 256
    >>> b = 256
    >>> a is b
    True
    >>> a = 257
    >>> b = 257
    >>> a is b
    False

    注意:c = d = [],mutable 对象 cd 是引用关系,指向同一个对象。

    1
    2
    3
    4
    5
    6
    7
    8
    >>> c = d = []
    >>> id(c)
    140537664175712
    >>> id(d)
    140537664175712
    >>> e = c
    >>> id(e)
    140537664175712

Python Garbage Collection