Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #43100 > unrolled thread
| Started by | Devin Jeanpierre <jeanpierreda@gmail.com> |
|---|---|
| First post | 2013-04-08 19:22 -0400 |
| Last post | 2013-04-08 19:22 -0400 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: How to subclass a family Devin Jeanpierre <jeanpierreda@gmail.com> - 2013-04-08 19:22 -0400
| From | Devin Jeanpierre <jeanpierreda@gmail.com> |
|---|---|
| Date | 2013-04-08 19:22 -0400 |
| Subject | Re: How to subclass a family |
| Message-ID | <mailman.307.1365463379.3114.python-list@python.org> |
On Mon, Apr 8, 2013 at 5:44 AM, Antoon Pardon
<antoon.pardon@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
Back to top | Article view | comp.lang.python
csiph-web