Refactoring similar subclasses

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Sep 10 22:00:14 EDT 2010


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?


-- 
Steven



More information about the Python-list mailing list