class Leaf(object):
"""A leaf falling in the woods."""
pass
leaf = Leaf()
leaf.color = "green"
leaf.color
'green'
这样添加的新属性只对当前定义的对象有效,不能在新对象上使用:
leaf2 = Leaf()
leaf2.color
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Input In [6], in <cell line: 1>() ----> 1 leaf2.color AttributeError: 'Leaf' object has no attribute 'color'
添加普通方法需要用def关键字定义。向Leaf类中添加一个新方法,表示树叶下落:
class Leaf(object):
"""A leaf falling in the woods."""
def fall(self, season="autumn"):
"""A leaf falls."""
print(f"A leaf falls in {season}!")
leaf = Leaf()
查看帮助:
leaf.fall?
调用该方法时,self参数不用传入,会自动转化为对象leaf,因此只需要传入season参数。不带参数时,season用默认值:
leaf.fall()
A leaf falls in autumn!
.__init__()
¶通常通过构造方法.__init__()
,在构造对象的时候添加属性。该方法在构造对象时会自动调用:
class Leaf(object):
"""A leaf falling in the woods."""
def __init__(self, color="green"):
self.color = color
leaf2 = Leaf("orange")
leaf2.color
'orange'
由于在.__init__()
函数中指定了默认参数,在构造时,也可以不传入color参数时,.color
属性为默认值“green”:
leaf = Leaf()
leaf.color
'green'