How to subclass a family

Devin Jeanpierre jeanpierreda at gmail.com
Mon Apr 8 19:22:16 EDT 2013


On Mon, Apr 8, 2013 at 5:44 AM, Antoon Pardon
<antoon.pardon at rece.vub.ac.be> wrote:
> Now of course I could subclass every class from the original family
> from Foo1 to Foon but that would mean a lot of duplicated code. Is
> there a way to reduce the use of duplicated code in such circumstances?

As a rule, if there's duplicate code you can stuff it in a function.

    def create_subclass(Foo):
        class Far(Foo):
            def boo(self, ...)
                do something different
                if whatever:
                    self.bar(...)
                else:
                    super(Far, self).boo(self, ...)
        return Far

    Far1 = create_subclass(Foo1)
    Far2 = create_subclass(Foo2)
    ...

Of course, this doesn't preserve the names of the subclasses properly.
To do that you can add a parameter, for the name, although this is a
little repetitive. Alternatively you can subclass yet again, as in:

    class Far1(create_subclass(Foo1)): pass

Or you can even change the approach to a class decorator that adds a method:

    def add_method(cls):
        def boo(self, ...):
            do something different
            if whatever:
                self.bar(...)
            else:
                super(cls, self).boo(...)

    @add_method
    class Far1(Foo1): pass

    @add_method
    class Far2(Foo2): pass

As a wise man once said, TIMTOWTDI. :(

-- Devin



More information about the Python-list mailing list