inheritance?

John Henry john106henry at hotmail.com
Wed Aug 16 17:49:24 EDT 2006



> 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.

Not automatically.

> 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

Maybe this would help:

class baseClass:
        def __init__(self, name):
                self.name=name
                print 'type'+self.name+' init'
        def fromfile(self, str):
                if (str == 'A'):
                        a = typeA()
                else:
                        a = typeB()
        def getName(self):
                print self.name

class typeA(baseClass):
        def __init__(self):
                baseClass.__init__(self, "A")
        def fromfile(self, str=None):
                print 'type'+self.name+' fromfile'

class typeB(baseClass):
        def __init__(self):
                baseClass.__init__(self, "B")
        def fromfile(self, str=None):
                print 'type'+self.name+' fromfile'

bcA = typeA()
bcA.fromfile()
bcA.getName()

bcB = typeB()
bcB.fromfile()
bc.getName()

I think you're looking at objects in an inverted way.

typeA is a kind of baseClass, and so is typeB.

not:

baseClass consists of 2 subclasses A and B.




More information about the Python-list mailing list