type cmp add

Robert Brewer fumanchu at amor.org
Fri Dec 3 22:44:06 CET 2004


Zora Honey wrote:
> 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).

a.__class__

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

self.__class__()


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org



More information about the Python-list mailing list