定义 class¶

基本形式¶

class 定义如下:

  1. class ClassName(ParentClass):
  2. """class docstring"""
  3. def method(self):
  4. return
  • class 关键词在最前面
  • ClassName 通常采用 CamelCase 记法
  • 括号中的 ParentClass 用来表示继承关系
  • 冒号不能缺少
  • """""" 中的内容表示 docstring,可以省略
  • 方法定义与函数定义十分类似,不过多了一个 self 参数表示这个对象本身
  • class 中的方法要进行缩进

In [1]:

  1. class Forest(object):
  2. """ Forest can grow trees which eventually die."""
  3. pass

其中 object 是最基本的类型。

查看帮助:

In [2]:

  1. import numpy as np
  2. np.info(Forest)
  1. Forest()
  2.  
  3. Forest can grow trees which eventually die.
  4.  
  5.  
  6. Methods:
  7.  

In [3]:

  1. forest = Forest()

In [4]:

  1. forest

Out[4]:

  1. <__main__.Forest at 0x3cda358>

添加方法和属性¶

可以直接添加属性(有更好的替代方式):

In [5]:

  1. forest.trees = np.zeros((150, 150), dtype=bool)

In [6]:

  1. forest.trees

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. forest2 = Forest()

forest2 没有这个属性:

In [8]:

  1. forest2.trees
  1. ---------------------------------------------------------------------------
  2. AttributeError Traceback (most recent call last)
  3. <ipython-input-8-42e6a9d57a8b> in <module>()
  4. ----> 1 forest2.trees
  5.  
  6. AttributeError: 'Forest' object has no attribute 'trees'

添加方法时,默认第一个参数是对象本身,一般为 self,可能用到也可能用不到,然后才是其他的参数:

In [9]:

  1. class Forest(object):
  2. """ Forest can grow trees which eventually die."""
  3. def grow(self):
  4. print "the tree is growing!"
  5.  
  6. def number(self, num=1):
  7. if num == 1:
  8. print 'there is 1 tree.'
  9. else:
  10. print 'there are', num, 'trees.'

In [10]:

  1. forest = Forest()
  2.  
  3. forest.grow()
  4. forest.number(12)
  1. the tree is growing!
  2. there are 12 trees.

原文: https://nbviewer.jupyter.org/github/lijin-THU/notes-python/blob/master/08-object-oriented-programming/08.04-writing-classes.ipynb