Steven D'Aprano wrote: > I have some code that currently takes four different classes, A, B, C and > D, and subclasses each of them in the same way: > > class MyA(A): > def method(self, x): > result = super(MyA, self).method(x) > if result == "spam": > return "spam spam spam" > return result > # many more methods overloaded > > > class MyB(B): > def method(self, x): > result = super(MyB, self).method(x) > if result == "spam": > return "spam spam spam" > return result > # many more methods overloaded > > > and so on, for MyC and MyD. There's a lot of duplicated code in there. > What techniques do you suggest for reducing the code duplication? I > thought about some variation of: > > names = "MyA MyB MyC MyD".split() > bases = [A, B, C, D] > d = dict-of-overloaded-methods > for name, base in zip(names, bases): > globals()[name] = type(name, [base], d) > > > but I'm not sure that this is a good approach, or how to inject the right > arguments to super in the dict. > > Any suggestions or guidelines?
You could use a mixin: class Mixin(object): def method(self, x): result = super(Mixin, self).method(x) if result == "spam": return "spam spam spam" return result # ... for name, base in zip(names, bases): globals()[name] = type(name, (Mixin, base), {}) Peter -- http://mail.python.org/mailman/listinfo/python-list