Programming in python: Using metaclasses to override methods of complex builtin on newest questions tagged python – Stack Overflow
As a learning exercise, I’m trying to implement a class which will emulate the behavior of python’s complex builtin, but with different behavior of the str and repr methods: I want them to print in the format
(1.0,2.0)
instead of
(1+2j)
I first tried simply subclassing from complex and redefining __str__ and __repr__, but this has the problem that when non-overridden methods are called, a standard complex is returned, printed in the standard format. I.e. I’d have
>>> a = ComplexWrapper(1.0,1.0)
>>> a
(1.0,1.0)
>>> b = ComplexWrapper(2.0,3.0)
>>> b
(2.0,3.0)
>>> a + b
(3+4j)
when the desired output is (3.0,4.0).
I was reading about metaclasses and thought they would solve my problem. Basing myself on the answer in Python Class Decorator, my current implementation is as follows:
def complex_str(z):
return '(' + str(z.real) + ',' + str(z.imag) + ')'
def complex_repr(z):
return '(' + repr(z.real) + ',' + repr(z.imag) + ')'
class CmplxMeta(type):
def __new__(cls, name, bases, attrs):
attrs['__str__'] = complex_str
attrs['__repr__'] = complex_repr
return super(CmplxMeta, cls).__new__(cls, name, bases, attrs)
class ComplexWrapper(complex):
__metaclass__ = CmplxMeta
Unfortunately, this seems to have the same behavior as the previous solution when e.g. two ComplexWrapper instances are added to each other.
I admit, I don’t fully understand metaclasses, and maybe my problem can be solved in a different way?
Of course I could manually redefine the relevant methods such as __add__, __subtract__, etc., but that would be very repetitive, so I would prefer a more elegant solution.
Any help appreciated.
source: http://stackoverflow.com/questions/10771010/using-metaclasses-to-override-methods-of-complex-builtin
Programming in python: programming-in-python
Recent Comments