假设下面的代码:
class my_class():
''' some code '''
@property
def x(self):
''' some initialization code '''
@property.setter
def x(self, val):
x = val
上面的代码适用于我的实现(在Windows上为3.4.2),但它是一种安全的方法吗?或者如果我从setter中的getter复制初始化代码会更好吗?
答案 0 :(得分:1)
正如BrenBarn所说,制定者并没有做你认为的事情。以下是如何做到这一点:
class my_class(object):
def __init__(self, x):
self._x = x # Or whatever name you want except x
@property
def x(self):
return self._x
@x.setter
def x(self, value):
"""
Do whatever you want in here (presumably you want to do *something*
otherwise why use the property decorator)?
"""
self._x = value