Python实例变量的默认值
示例
如果变量包含不可变类型的值(例如字符串),则可以分配这样的默认值
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的位置未更改另请参见可变默认参数和“最小惊讶”和可变默认参数。
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短