我读了一些关于吸气剂和二传手的信息,但还没有想到它。我的一个问题是 init 方法中的声明:如果方法需要参数,我怎么才能只改变一个属性?当然也欢迎任何其他方法。
class States:
def __init__(self, f=0, n=0):
self.state = n
self.level_state = f
@property
def state(self, n):
return self._state
@state.setter
def state(self, n):
self._state = n
@property
def level_state(self, f):
return self._level_state
@level_state.setter
def state(self, f):
self._level_state = f
示例情况,单独更改属性:
Situation1:
States().state = 3
Situation2:
States().level_state = 2
答案 0 :(得分:0)
代码不起作用,因为您已将基础属性命名为与相应属性相同。
您需要使用与getters / setters引用的属性相同的属性名称:
class States:
def __init__(self, f=0, n=0):
self._state = n # <-- changed here
self._level_state = f # <-- changed here
@property
def state(self, n):
return self._state
@state.setter
def state(self, n):
self._state = n
@property
def level_state(self, f):
return self._level_state
@level_state.setter
def state(self, f):
self._level_state = f
但这种情况的简单解决方案是根本不使用属性:
class States:
def __init__(self, f=0, n=0):
self.state = n
self.level_state = f
# done