[英]Can I use a property name inside the same property's `setter`?
Assuming the code below: 假设下面的代码:
class my_class():
''' some code '''
@property
def x(self):
''' some initialization code '''
@property.setter
def x(self, val):
x = val
The above code works on my implementation (3.4.2 on Windows) but is it a safe way to do this or will it be better if I duplicated the initialization code from getter in the setter? 上面的代码适用于我的实现(在Windows上为3.4.2),但这是一种安全的方法,还是如果我在setter中复制了getter的初始化代码,会更好吗?
As BrenBarn mentioned, the setter doesn't do what you think it does. 正如布伦·巴恩(BrenBarn)所提到的,二传手并没有按照自己的想法去做。 Here's how to do this right:
这是正确执行此操作的方法:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.