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


Groups > comp.lang.python > #43092

Re: How to subclass a family

References <51629193.6050301@rece.vub.ac.be>
Date 2013-04-08 22:17 +0100
Subject Re: How to subclass a family
From Arnaud Delobelle <arnodel@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.302.1365455826.3114.python-list@python.org> (permalink)

Show all headers | View raw


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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

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

csiph-web