Problems with inheritance (and factory functions).

laotseu bdesth at nospam.free.fr
Sun Dec 29 20:52:08 EST 2002


Rocco Rossi wrote:
> Hi all.
> 
> I've had this sort of problem on different occasions and totally different
> circumstances.
> Here it is:
> 
> In the first case I needed to write a Partlcle class (for solving physics
> problems), and I did it pretty
> easily enough. Now I included in this class all the methods (and some
> operator methods) I needed, and that worked very nicely too.
> 
> The problem came up when I tried to specialize my class by inheritance. I
> wanted to create a Spin-Particle class
> which had a member variable representing the "spin" value of the particle
> (1/2, 1, etc.). I found out that some
> of the methods which were inherited from the super-class continued
> (obviously!) to return values of Particle type
> which wasn't what I wanted. I needed them to adjust accordingly and return
> values of the new type, but of course this
> wasn't possible.
> 
> I had this same problem another time although the situation was very
> different. I wanted to create my own MySocket class
> inheriting from the well-known library Socket class, and all I wanted was to
> add some specialized methods of mine to accomplish some specific tasks. I
> found out though that the "connect" method in the base class Socket creates
> new instances
> of Socket type, and of course that is exactly what was going on with the
> MySocket class too, so basically every time I
> succeeded in making a connection what I got was new instances of Socket type
> which had none of the new methods that I
> added and wanted in the first place.
> 
> Is there some solution (design pattern) that can overcome problems like this
> one???
> 
> Thanks.
> 
> Rock
> 
> 
> 

No need for patterns, but you need to override some methods of the base 
class in the derived class. Every method you don't override just keep on 
working *exactly* the same.

ie :

class Base:
     def __init__(self, name):
         self.name = name
     def getName(self):
         return self.name

class Derived1(Base):
     def __init__(self, name, number):
         Base.__init__(self, name)
         self.number = number

class Derived2(Base):
     def __init__(self, name, number):
         Base.__init__(self, name)
         self.number = number
     def getName(self):
         return self.name + "-" + str(self.number)


 >>>b = base("base")
 >>>d1 = Derived1("d1", 1)
 >>>d2 = Derived2("d2", 2)
 >>>b.getName()
"base"
 >>>d1.getName()
"d1"
 >>>d2.getName()
"d2-2"

Here the getName() method of Derived1 *is* the getName() method of Base, 
whereas the getName() method of Derived2 is different...


Laotseu




More information about the Python-list mailing list