代码拉取完成,页面将自动刷新
同步操作将从 OpenDocCN/ailearning 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
class
定义如下:
class ClassName(ParentClass):
"""class docstring"""
def method(self):
return
class
关键词在最前面ClassName
通常采用 CamelCase
记法ParentClass
用来表示继承关系""""""
中的内容表示 docstring
,可以省略self
参数表示这个对象本身class
中的方法要进行缩进In [1]:
class Forest(object):
""" Forest can grow trees which eventually die."""
pass
其中 object
是最基本的类型。
查看帮助:
In [2]:
import numpy as np
np.info(Forest)
Forest()
Forest can grow trees which eventually die.
Methods:
In [3]:
forest = Forest()
In [4]:
forest
Out[4]:
<__main__.Forest at 0x3cda358>
可以直接添加属性(有更好的替代方式):
In [5]:
forest.trees = np.zeros((150, 150), dtype=bool)
In [6]:
forest.trees
Out[6]:
array([[False, False, False, ..., False, False, False],
[False, False, False, ..., False, False, False],
[False, False, False, ..., False, False, False],
...,
[False, False, False, ..., False, False, False],
[False, False, False, ..., False, False, False],
[False, False, False, ..., False, False, False]], dtype=bool)
In [7]:
forest2 = Forest()
forest2
没有这个属性:
In [8]:
forest2.trees
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-8-42e6a9d57a8b> in <module>()
----> 1 forest2.trees
AttributeError: 'Forest' object has no attribute 'trees'
添加方法时,默认第一个参数是对象本身,一般为 self
,可能用到也可能用不到,然后才是其他的参数:
In [9]:
class Forest(object):
""" Forest can grow trees which eventually die."""
def grow(self):
print "the tree is growing!"
def number(self, num=1):
if num == 1:
print 'there is 1 tree.'
else:
print 'there are', num, 'trees.'
In [10]:
forest = Forest()
forest.grow()
forest.number(12)
the tree is growing!
there are 12 trees.
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。