Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #43092 > unrolled thread

Re: How to subclass a family

Started byArnaud Delobelle <arnodel@gmail.com>
First post2013-04-08 22:17 +0100
Last post2013-04-08 22:17 +0100
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.


Contents

  Re: How to subclass a family Arnaud Delobelle <arnodel@gmail.com> - 2013-04-08 22:17 +0100

#43092 — Re: How to subclass a family

FromArnaud Delobelle <arnodel@gmail.com>
Date2013-04-08 22:17 +0100
SubjectRe: How to subclass a family
Message-ID<mailman.302.1365455826.3114.python-list@python.org>
On 8 April 2013 10:44, Antoon Pardon <antoon.pardon@rece.vub.ac.be> 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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web