inheritance?

KraftDiner bobrien18 at yahoo.com
Wed Aug 16 14:07:08 EDT 2006


Steven D'Aprano wrote:
> On Tue, 15 Aug 2006 19:35:11 -0700, KraftDiner wrote:
>
> > I have two classes:
> >
> > class implicitClass:
> >    def __init__(self):
> >    def isIVR(self):  #This is a class private method.
>
> The convention is to flag classes as "private" with a leading underscore:
>
>     def _isIVR(self):
>
> or double underscores for "really private, no, honestly":
>
>     def __isIVR(self):
>
> but google on "python name mangling" before using that.
>
> [snip]
>
> > As you can see the interface is almost identical.
> >
> > How can I define a base class that will abstract
> > the type such that I don't know if its really and inplicit
> > or explicit object?
>
> Something like this?
>
>
> class baseClass:
>    def __init__(self):
>        raise NotImplementedError("Don't instantiate the base class!")
>    def fromfile(self):
>    def getElement(self):
>    # etc.
>
>
> class implicitClass(baseClass):
>    def __init__(self):
>        # code
>    def _isIVR(self):
>        # code
>    def fromfile(self, fileObj, byteOrder):
>        # code
> # etc.
>
> Now, you can define instance = implicitClass() or explicitClass(). When
> you come to use instance, you don't need to know whether it is one or the
> other. If you need to type-test, call "isinstance(instance, baseClass)".
>
> The only minor issue is that the fromfile method has a different
> interface. If you really want to do duck typing, they need to have the
> same interface. That might be as simple as:
>
> class explicitClass(baseClass):
>    def fromfile(self, fileObj, byteOrder=None):
>        # byteOrder is ignored; it is included only for
>        # compatibility with implicitClass
>
>
> Is that what you're asking for?
>
>
Here I tried this example and maybe this will explain the difficulties
I'm having.
1) at the time the baseClass is constructed shouldn't the constructor
of the appropriate
type be called.
2) getName is doing nothing...

class baseClass:
	def __init__(self):
		pass
	def fromfile(self, str):
		if (str == 'A'):
			a = typeA()
		else:
			a = typeB()
	def getName(self):
		pass

class typeA(baseClass):
	def __init__(self):
		self.name='A'
		print 'typeA init'
	def fromfile(self, str=None):
		print 'typeA fromfile'
	def getName(self):
		print self.name

class typeB(baseClass):
	def __init__(self):
		self.name='B'
		print 'typeB init'
	def fromfile(self, str=None):
		print 'typeB fromfile'
	def getName(self):
		print self.name

bc = baseClass()
bc.fromfile('A')
bc.getName()
bc.fromfile('B')
bc.getName()
bc.getName()

log:
typeA init
typeB init






> 
> -- 
> Steven D'Aprano




More information about the Python-list mailing list