如果变量包含不可变类型的值(例如字符串),则可以分配这样的默认值
class Rectangle(object): def __init__(self, width, height, color='blue'): self.width= width self.height= height self.color= color def area(self): returnself.width *self.height # 创建类的一些实例 default_rectangle = Rectangle(2, 3) print(default_rectangle.color) # 蓝色 red_rectangle = Rectangle(2, 3, 'red') print(red_rectangle.color) # 红
在初始化可变对象(例如构造函数中的列表)时,需要小心。考虑以下示例:
class Rectangle2D(object): def __init__(self, width, height, pos=[0,0], color='blue'): self.width= width self.height= height self.pos= pos self.color= color r1 = Rectangle2D(5,3) r2 = Rectangle2D(7,8) r1.pos[0] = 4 r1.pos # [4,0] r2.pos # [4,0] r2's pos has changed as well
此行为是由于以下事实引起的:在Python中,默认参数是在函数执行时绑定的,而不是在函数声明时绑定的。要获得实例之间不共享的默认实例变量,应使用如下结构:
class Rectangle2D(object): def __init__(self, width, height, pos=None, color='blue'): self.width= width self.height= height self.pos= pos or [0, 0] # 默认值为[0,0] self.color= color r1 = Rectangle2D(5,3) r2 = Rectangle2D(7,8) r1.pos[0] = 4 r1.pos # [4,0] r2.pos # [0,0] r2的位置未更改
另请参见可变默认参数和“最小惊讶”和可变默认参数。