type cmp add

Z

Zora Honey

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,212
Messages
2,571,101
Members
47,697
Latest member
looped_monk

Latest Threads

Top