Determining if a superclass is being initialized from a derived class

Robert Roy rjroy at takingcontrol.com
Sun Jan 21 10:07:30 EST 2001


On Sat, 20 Jan 2001 16:14:06 -0800, Timothy Grant
<tjg at exceptionalminds.com> wrote:

>Hi folk,
>
>I have a superclass that I'm using for a project. The superclass has a
>debugging function that is called whenever the command line option --debug
>is used.
>
>I have run into a situation where I need to subclass the superclass. I want
>access to the debugging information, but not until after the subclass is
>fully initialized.
>
>class superclass:
>	def __init__(self):
>		self.a = 1
>		self.b = 2
>		if self.debug:
>			self.dodebug()
>	def dodebug():
>		print self.a
>		print self.b
>
>
>class subclass(superclass):
>	def __init__(self):
>		superclass.__init__(self)
>
>		self.a = 2
>		self.b = 4
>
>		if self.debug:
>			self.dodebug()
>
>In the above, dodebug() is called twice. I would like to only call it the
>second time.
>
>Enlightenment would be greatly appreciated.
>

Here is a really ugly way to do it...
NOT recommended...

class uglysubclass(superclass):
	def __init__(self):
		debug = self.debug
		self.debug = 0
		superclass.__init__(self)
		self.a = 2
		self.b = 4
		self.debug = debug

		if self.debug:
			self.dodebug()


I am sure there are a million variations on this theme as well....


If the only difference between the classes is the initialisation, then
don't subclass at all.
class superclass:
	def __init__(self, a=1, b=2):
		self.a = a
		self.b = b
		if self.debug:
			self.dodebug()
and perhaps use a factory function in the module to simplify the user
interface. 

def getStandard():
	return superclass()

def getSpecial():
	return superclass(2,4)

def getExtraSpecial(a, b):
	return superclass(a,b)

The bonus of this is that if you later decide you need to subclass,
you can do it without changing any client code (providing the
interface remains consistent. Thus if you created a subclass
specialsubclass you would simply rewrite getSpecial to return an
instance of specialsubclass

def getSpecial():
	return specialsubclass(2,4)




If you need to subclass, then my choice would be to move the variable
initalisation into another method. The use of factory functions is
equally valid in this scenario.

class superclass:
	def __init__(self):
		self.initialise()
		if self.debug:
			self.dodebug()

	def initialise(self):
		self.a = 1
		self.b = 2

	def dodebug():
		print self.a
		print self.b


class subclass(superclass):
	def initialise(self):
		self.a = 2
		self.b = 4



Bob



More information about the Python-list mailing list