Refactoring similar subclasses

Peter Otten __peter__ at web.de
Sat Sep 11 08:53:38 CEST 2010


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



More information about the Python-list mailing list