Skip to content Skip to sidebar Skip to footer

How To Handle Innerclass Attribute Dependencies?

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 you

Solution 1:

You would have to use a custom subclass of list to detect changes:

classMyList(list):
    on_change_callback = Nonedef_notify(self):
        if self.on_change_callback isnotNone:
            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.

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.

Solution 2:

To allow discussion and increase creativity I want to offer the following solution myself:

classAccumulator(object):def__init__(self,all_things):
       #:param all_things: a sequence or generator of stuff of any kindself.__all_things = tuple(all_things)

    @propertydefall_things(self):
        returnself.__all_things

    @propertydefall_things(self, all_things):
        self.__all_things = tuple(all_things)

It's clean, it's read-only and nothing can go wrong or be misused. Now the same assumption applies as in the question's structure: You need to reset it, if you want to change it. But you don't have to tell the user, because it's his only chance. If the user still wonders why, he can read the hopefully verbose class docstring.

Post a Comment for "How To Handle Innerclass Attribute Dependencies?"