#!/usr/bin/env python # coding: utf-8 # # 方法与属性 # # 自定义类型中通常要定义一些方法和属性。 # # ## 手动添加属性 # # 属性可以手动添加: # In[1]: class Leaf(object): """A leaf falling in the woods.""" pass # In[2]: leaf = Leaf() # In[3]: leaf.color = "green" # In[4]: leaf.color # 这样添加的新属性只对当前定义的对象有效,不能在新对象上使用: # In[5]: leaf2 = Leaf() # In[6]: leaf2.color # ## 添加普通方法 # # 添加普通方法需要用def关键字定义。向Leaf类中添加一个新方法,表示树叶下落: # In[7]: class Leaf(object): """A leaf falling in the woods.""" def fall(self, season="autumn"): """A leaf falls.""" print(f"A leaf falls in {season}!") # In[8]: leaf = Leaf() # 查看帮助: # In[9]: get_ipython().run_line_magic('pinfo', 'leaf.fall') # 调用该方法时,self参数不用传入,会自动转化为对象leaf,因此只需要传入season参数。不带参数时,season用默认值: # In[10]: leaf.fall() # ## 构造方法`.__init__()` # 通常通过构造方法`.__init__()`,在构造对象的时候添加属性。该方法在构造对象时会自动调用: # In[11]: class Leaf(object): """A leaf falling in the woods.""" def __init__(self, color="green"): self.color = color # In[12]: leaf2 = Leaf("orange") # In[13]: leaf2.color # 由于在`.__init__()`函数中指定了默认参数,在构造时,也可以不传入color参数时,`.color`属性为默认值“green”: # In[14]: leaf = Leaf() # In[15]: leaf.color # In[ ]: