Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Re: How to subclass a family

Reply
Thread Tools

Re: How to subclass a family

 
 
Devin Jeanpierre
Guest
Posts: n/a
 
      04-08-2013
On Mon, Apr 8, 2013 at 5:44 AM, Antoon Pardon
<(E-Mail Removed)> 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
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
How to subclass a family Antoon Pardon Python 1 04-09-2013 02:52 AM
Re: How to subclass a family Arnaud Delobelle Python 0 04-08-2013 09:17 PM
Re: How include a large array? Edward A. Falk C Programming 1 04-04-2013 08:07 PM
String subclass method returns subclass - bug or feature? S.Volkov Ruby 2 03-12-2006 06:46 PM
subclass has a variable that is subclass of same superclass jstorta Java 3 02-20-2006 08:42 PM



Advertisments