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?
As BrenBarn mentioned, the setter doesn't do what you think it does. 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.