Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #43100
| References | <51629193.6050301@rece.vub.ac.be> |
|---|---|
| From | Devin Jeanpierre <jeanpierreda@gmail.com> |
| Date | 2013-04-08 19:22 -0400 |
| Subject | Re: How to subclass a family |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.307.1365463379.3114.python-list@python.org> (permalink) |
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 comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: How to subclass a family Devin Jeanpierre <jeanpierreda@gmail.com> - 2013-04-08 19:22 -0400
csiph-web