【发布时间】:2020-03-26 10:08:20
【问题描述】:
当类的任何属性被修改时,是否有一些通用的方法可以让类运行函数?我想知道是否可以运行某些子进程来监视对类的更改,但也许有一种方法可以从 class 继承并修改一些作为 Python 类一部分的 on_change 函数,有点像默认的 @987654324可以修改类的@方法。这里有什么明智的方法?
实际的应用程序不仅仅是打印输出,而是更新数据库中与实例化类的数据属性相对应的条目。
#!/usr/bin/env python
class Event(object):
def __init__(self):
self.a = [10, 20, 30]
self.b = 15
#def _on_attribute_change(self):
# print(f'attribute \'{name_of_last_attribute_that_was_changed}\' changed')
event = Event()
event.a[1] = 25
# printout should happen here: attribute 'a' changed
event.a.append(35)
# printout should happen here: attribute 'a' changed
event.c = 'test'
# printout should happen here: attribute 'c' changed
【问题讨论】:
-
这能回答你的问题吗? How to trigger function on value change?
标签: python class attributes