Oct-19-2020, 04:05 AM
If you think of a Python class as a dictionary you have a pretty accurate picture of how it works. When I do a "def method_name" inside the class it adds "method_name" to a dictionary in the class with a value that is the class.method_name function. Creating a class variable does the same thing, except the value in the dictionary is the object referenced by the class variable name.
Since classes are essentially dictionaries with some syntactic sugar, you can add methods from anywhere and at any time. You can also add methods to instances of classes so that two instances do different things when the same method name is used. This is usually a bad idea, but there are times when it can be useful.
I don't know what you are trying to do, but here is something I did which may be similar. I have a class named Model. A model is a collection of models/parts. I have no idea what parts a model may contain or what those parts can do, but I commonly ask all a model's parts to do the same thing. For this I use "forall".
Since classes are essentially dictionaries with some syntactic sugar, you can add methods from anywhere and at any time. You can also add methods to instances of classes so that two instances do different things when the same method name is used. This is usually a bad idea, but there are times when it can be useful.
I don't know what you are trying to do, but here is something I did which may be similar. I have a class named Model. A model is a collection of models/parts. I have no idea what parts a model may contain or what those parts can do, but I commonly ask all a model's parts to do the same thing. For this I use "forall".
def forall(self, func_name, *args, **kwargs): """Have all my parts execute the named function""" for part in self._parts: if (func := getattr(part, func_name, None)) is not None: func(part, *args, **kwargs) return self