检测类属性值更改,然后更改另一个类属性 [英] Detecting class attribute value change and then changing another class attribute
本文介绍了检测类属性值更改,然后更改另一个类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
比方说我有一个叫做Number的课
Let's say I have a class called Number
class Number():
def __init__(self,n):
self.n=n
self.changed=None
a = Number(8)
print(a.n) #prints 8
a.n=9
print(a.n) #prints 9
当 n
类属性更改时,我希望将 changed
类属性更改为 True
.
When the n
class attribute changes, I want the changed
class attribute to be changed to True
.
推荐答案
可以正确使用 @propety
class Number():
def __init__(self,n):
self._n=n
self._changed=None
@property
def n(self):
return self._n
@property
def changed(self):
return self._changed
@n.setter
def n(self, val):
# while setting the value of n, change the 'changed' value as well
self._n = val
self._changed = True
a = Number(8)
print(a.n) #prints 8
a.n=9
print(a.n) #prints 9
print(a.changed)
返回:
8
9
True
这篇关于检测类属性值更改,然后更改另一个类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文