什么是对象?¶

Python 中,几乎所有的东西都是对象。

整数是对象:

In [1]:

  1. a = 257

In [2]:

  1. type(a)

Out[2]:

  1. int

In [3]:

  1. id(a)

Out[3]:

  1. 53187032L

ba 是同一个对象:

In [4]:

  1. b = a

In [5]:

  1. id(b)

Out[5]:

  1. 53187032L

In [6]:

  1. c = 258
  2. id(c)

Out[6]:

  1. 53186960L

函数:

In [7]:

  1. def foo():
  2. print 'hi'

In [8]:

  1. type(foo)

Out[8]:

  1. function

In [9]:

  1. id(foo)

Out[9]:

  1. 63632664L

type 函数本身也是对象:

In [10]:

  1. type(type)

Out[10]:

  1. type

In [11]:

  1. id(type)

Out[11]:

  1. 506070640L

只有一些保留的关键词不是对象:

In [12]:

  1. id(if)
  1. File "<ipython-input-12-1e0d1307109a>", line 1
  2. id(if)
  3. ^
  4. SyntaxError: invalid syntax

In [13]:

  1. id(+)
  1. File "<ipython-input-13-86853fe3c6fd>", line 1
  2. id(+)
  3. ^
  4. SyntaxError: invalid syntax

原文: https://nbviewer.jupyter.org/github/lijin-THU/notes-python/blob/master/08-object-oriented-programming/08.03-what-is-a-object.ipynb