特殊方法¶

Python 使用 __ 开头的名字来定义特殊的方法和属性,它们有:

  • init()
  • repr()
  • str()
  • call()
  • iter()
  • add()
  • sub()
  • mul()
  • rmul()
  • class
  • name

构造方法 init()¶

之前说到,在产生对象之后,我们可以向对象中添加属性。事实上,还可以通过构造方法,在构造对象的时候直接添加属性:

In [1]:

  1. class Leaf(object):
  2. """
  3. A leaf falling in the woods.
  4. """
  5. def __init__(self, color='green'):
  6. self.color = color

默认属性值:

In [2]:

  1. leaf1 = Leaf()
  2.  
  3. print leaf1.color
  1. green

传入有参数的值:

In [3]:

  1. leaf2 = Leaf('orange')
  2.  
  3. print leaf2.color
  1. orange

回到森林的例子:

In [4]:

  1. import numpy as np
  2.  
  3. class Forest(object):
  4. """ Forest can grow trees which eventually die."""
  5. def __init__(self):
  6. self.trees = np.zeros((150,150), dtype=bool)
  7. self.fires = np.zeros((150,150), dtype=bool)

我们在构造方法中定义了两个属性 treesfires

In [5]:

  1. forest = Forest()
  2.  
  3. forest.trees

Out[5]:

  1. array([[False, False, False, ..., False, False, False],
  2. [False, False, False, ..., False, False, False],
  3. [False, False, False, ..., False, False, False],
  4. ...,
  5. [False, False, False, ..., False, False, False],
  6. [False, False, False, ..., False, False, False],
  7. [False, False, False, ..., False, False, False]], dtype=bool)

In [6]:

  1. forest.fires

Out[6]:

  1. array([[False, False, False, ..., False, False, False],
  2. [False, False, False, ..., False, False, False],
  3. [False, False, False, ..., False, False, False],
  4. ...,
  5. [False, False, False, ..., False, False, False],
  6. [False, False, False, ..., False, False, False],
  7. [False, False, False, ..., False, False, False]], dtype=bool)

修改属性的值:

In [7]:

  1. forest.trees[0,0]=True
  2. forest.trees

Out[7]:

  1. array([[ True, False, False, ..., False, False, False],
  2. [False, False, False, ..., False, False, False],
  3. [False, False, False, ..., False, False, False],
  4. ...,
  5. [False, False, False, ..., False, False, False],
  6. [False, False, False, ..., False, False, False],
  7. [False, False, False, ..., False, False, False]], dtype=bool)

改变它的属性值不会影响其他对象的属性值:

In [8]:

  1. forest2 = Forest()
  2.  
  3. forest2.trees

Out[8]:

  1. array([[False, False, False, ..., False, False, False],
  2. [False, False, False, ..., False, False, False],
  3. [False, False, False, ..., False, False, False],
  4. ...,
  5. [False, False, False, ..., False, False, False],
  6. [False, False, False, ..., False, False, False],
  7. [False, False, False, ..., False, False, False]], dtype=bool)

事实上,new() 才是真正产生新对象的方法,init() 只是对对象进行了初始化,所以:

  1. leaf = Leaf()

相当于

  1. my_new_leaf = Leaf.__new__(Leaf)
  2. Leaf.__init__(my_new_leaf)
  3. leaf = my_new_leaf

表示方法 repr() 和 str()¶

In [9]:

  1. class Leaf(object):
  2. """
  3. A leaf falling in the woods.
  4. """
  5. def __init__(self, color='green'):
  6. self.color = color
  7. def __str__(self):
  8. "This is the string that is printed."
  9. return "A {} leaf".format(self.color)
  10. def __repr__(self):
  11. "This string recreates the object."
  12. return "{}(color='{}')".format(self.__class__.__name__, self.color)

str() 是使用 print 函数显示的结果:

In [10]:

  1. leaf = Leaf()
  2.  
  3. print leaf
  1. A green leaf

repr() 返回的是不使用 print 方法的结果:

In [11]:

  1. leaf

Out[11]:

  1. Leaf(color='green')

回到森林的例子:

In [12]:

  1. import numpy as np
  2.  
  3. class Forest(object):
  4. """ Forest can grow trees which eventually die."""
  5. def __init__(self, size=(150,150)):
  6. self.size = size
  7. self.trees = np.zeros(self.size, dtype=bool)
  8. self.fires = np.zeros((self.size), dtype=bool)
  9.  
  10. def __repr__(self):
  11. my_repr = "{}(size={})".format(self.__class__.__name__, self.size)
  12. return my_repr
  13.  
  14. def __str__(self):
  15. return self.__class__.__name__

In [13]:

  1. forest = Forest()

str() 方法:

In [14]:

  1. print forest
  1. Forest

repr() 方法:

In [15]:

  1. forest

Out[15]:

  1. Forest(size=(150, 150))

nameclass 为特殊的属性:

In [16]:

  1. forest.__class__

Out[16]:

  1. __main__.Forest

In [17]:

  1. forest.__class__.__name__

Out[17]:

  1. 'Forest'

原文: https://nbviewer.jupyter.org/github/lijin-THU/notes-python/blob/master/08-object-oriented-programming/08.05-special-method.ipynb