如何处理内部类属性依赖关系? [英] How to handle innerclass attribute dependencies?
问题描述
如果要更改属性的类on change
中的其他变量,只需为它编写一个property
即可.如果您有简单的数据类型,那很好.但是,如果您的变量包含复杂的类型(如列表)(不是很不典型),则可以更改内容本身,而无需再次调用variable.setter
.
In case you want to change other variables in a class on change
of an attribute you simply just write a property
for it. That works fine, if you have a simple data type. But if your variable contains a complex type like a list (not so untypical), the content itself can be changed without calling the variable.setter
again.
是否可以使用任何回调或事件来跟踪对类的列表属性的更改?还有什么其他方法可以使代码保持干净,又不破坏类的内部功能?
Are there any callbacks or events that can be used to track changes to a list attribute of a class? What else can be done to keep the code clean and not destroy the inner functionality of the class?
示例:
class Accumulator(object)
def __init__(self,all_things):
# :param all_things: a list of stuff of any kind
self.__all_things = all_things
@property
def all_things(self):
return self.__all_things
@all_things.setter
def all_things(self,input):
self.__all_things = input
跳出框框思考可能是解决方案.首要任务不是使类结构保持活动状态,而是找到一种有效且允许使用干净API的模式!
Thinking outside the box is probably the solution. The priority is not to keep the class structure alive, but to find a pattern that works and allows a clean API!
推荐答案
您将不得不使用list的自定义子类来检测更改:
You would have to use a custom subclass of list to detect changes:
class MyList(list):
on_change_callback = None
def _notify(self):
if self.on_change_callback is not None:
self.on_change_callback(self)
def __setitem__(self, index, value):
super(MyList, self).__setitem__(self, index, value)
self._notify()
# Etc, each mutating method needs to be overridden.
您需要覆盖每个变异方法,调用原始方法(通过super()
),然后调用self._notify()
.有关方法列表,请参见模拟容器类型部分.
You'd need to override each mutating method, call the original method (through super()
), then call self._notify()
. For a list of methods, see the Emulating container types section.
这篇关于如何处理内部类属性依赖关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!