type cmp add

Zora Honey zhoney at bornbybits.com
Fri Dec 3 15:41:46 EST 2004


I've just discovered operator overloading via defining a class's special
methods and I think it's swell, or would be if I could figure out two
things:

In order say, add things, I need to do some type checking. For a+b to
work, both must be instances of the same class.  I can check to see if
they are instances using if type(a)==types.InstanceType, but I don't
know how determine which class it is in an instance of.  (This must
somehow be possible because if I do "print a" without having overloaded
__str__, I get <__main__.C instance at 0x815b9ec> telling me it's an
instance of class C).

Also, how to I make an instance of a class from within the class?  I
want c = a + b to return a new instance of value a + b without changing
a or b.  When I define the __add__ method, I have access to self and
other, whose properties I can change at will, but how do I get a fresh
instance of the class that I am writing?

Thanks,
zh




More information about the Python-list mailing list