Problems with inheritance (and factory functions).

Simon Burton simonb at webone.com.au
Sun Dec 29 18:09:00 EST 2002


On Sun, 29 Dec 2002 17:02:28 +0000, 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.
> 

Yup, i hear ya.
The solution i cam up with is to use the __class__ attribute.
eg.

class Base:
  def clone(self):
    return self.__class__()

Then if i call clone on any derived class i get an instance of that class
back.

I reckon it's a design pattern; pro'ly most design patterns are one liners
in python, tho'.

happy hacking,
Simon Burton.




More information about the Python-list mailing list