I have several classes where I want to add a single property to each class (its md5 hash value) and calculate that hash value when initializing objects of that class, but otherwise maintain everything else about the class. Is there any more elegant way to do that in python than to create a subclass for all the classes where I want to change the initialization and add the property?
Asked
Active
Viewed 95 times
-2
-
1Have you considered creating a mix-in class? See e.g. http://stackoverflow.com/q/533631/3001761 – jonrsharpe Jun 29 '14 at 17:00
1 Answers
0
You can add properties and override __init__
dynamically:
def newinit(self, orig):
orig(self)
self._md5 = #calculate md5 here
_orig_init = A.__init__
A.__init__ = lambda self: newinit(self, _orig_init)
A.md5 = property(lambda self: self._md5)
However, this can get quite confusing, even once you use more descriptive names than I did above. So I don't really recommend it.
Cleaner would probably be to simply subclass, possibly using a mixin class if you need to do this for multiple classes. You could also consider creating the subclasses dynamically using type()
to cut down on the boilerplate further, but clarity of code would be my first concern.

otus
- 5,572
- 1
- 34
- 48