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
I first tried simply subclassing from
complex and redefining
__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
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
__subtract__, etc., but that would be very repetitive, so I would prefer a more elegant solution.
Any help appreciated.
Programming in python: programming-in-python