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

 
 
Arnaud Delobelle
Guest
Posts: n/a
 
      04-08-2013
On 8 April 2013 10:44, Antoon Pardon <(E-Mail Removed)> wrote:
> Here is the idea. I have a number of classes with the same interface.
> Something like the following:
>
> class Foo1:
> def bar(self, ...):
> work
> def boo(self, ...):
> do something
> self.bar(...)
>
> What I want is the equivallent of:
>
> class Far1(Foo1):
> def boo(self, ...)
> do something different
> if whatever:
> self.bar(...)
> else:
> Foo1.boo(self, ...)
>
> 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?
>


(Python 3)
------------------------------
class Foo1:
def bar(self):
print('Foo1.bar')
def boo(self, whatever):
print('Foo1.boo', whatever)
self.bar()

# class Foo2: ...(I'll let you define this one)

class DifferentBoo:
def boo(self, whatever):
print('DifferentBoo.boo', whatever)
if whatever:
self.bar()
else:
super().boo(whatever)

class Far1(DifferentBoo, Foo1): pass
# class Far2(DifferentBoo, Foo2): pass

------------------------------
>>> foo = Foo1()
>>> foo.bar()

Foo1.bar
>>> foo.boo(1)

Foo1.boo 1
Foo1.bar
>>> far = Far1()
>>> far.bar()

Foo1.bar
>>> far.boo(0)

DifferentBoo.boo 0
Foo1.boo 0
Foo1.bar
>>> far.boo(1)

DifferentBoo.boo 1
Foo1.bar

HTH,

--
Arnaud
 
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 include a large array? Edward A. Falk C Programming 1 04-04-2013 08:07 PM
subclass a class in the namespace of the that subclass Trans Ruby 8 10-23-2008 07:24 AM
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