使用getter和setter的pythonic方法是什么?我这样做就像:def set_property(property,value): def get_property(property):或object.property = value
value = object.property我是Python的新手,所以我仍然在探索语法,我想要一些关于这方面的建议。
3 回答
慕姐4208626
TA贡献1852条经验 获得超7个赞
class C(object): def __init__(self): self._x = None @property def x(self): """I'm the 'x' property.""" print("getter of x called") return self._x @x.setter def x(self, value): print("setter of x called") self._x = value @x.deleter def x(self): print("deleter of x called") del self._x c = C()c.x = 'foo' # setter calledfoo = c.x # getter calleddel c.x # deleter called
慕尼黑的夜晚无繁华
TA贡献1864条经验 获得超6个赞
In [1]: class test(object): def __init__(self): self.pants = 'pants' @property def p(self): return self.pants @p.setter def p(self, value): self.pants = value * 2 ....: In [2]: t = test()In [3]: t.pOut[3]: 'pants'In [4]: t.p = 10In [5]: t.pOut[5]: 20
添加回答
举报
0/150
提交
取消