Using metaclasses to override methods of complex builtin

淺唱寂寞╮ 提交于 2019-12-02 21:06:58

Your current approach won't work. How you define your class isn't the issue -- the methods of complex are creating new instances of complex when you call them, rather than using the type of the input objects. You'll always get back instances of complex rather than ComplexWrapper, so your customized methods won't be called:

>>> type(ComplexWrapper(1.0,1.0) + ComplexWrapper(2.0,3.0))
<type 'complex'>

Instead, you need to convert the new complex objects returned by the methods of complex to return objects of the derived class.

This metaclass wraps all the methods of the specified base class and attaches the wrapped methods to the class. The wrapper checks if the value to be returned is an instance of the base class (but excluding instances of subclasses), and if it is, converts it to an instance of the derived class.

class ReturnTypeWrapper(type):
    def __new__(mcs, name, bases, dct):
        cls = type.__new__(mcs, name, bases, dct)
        for attr, obj in cls.wrapped_base.__dict__.items():
            # skip 'member descriptor's and overridden methods
            if type(obj) == type(complex.real) or attr in dct:
                continue
            if getattr(obj, '__objclass__', None) is cls.wrapped_base:
                setattr(cls, attr, cls.return_wrapper(obj))
        return cls

    def return_wrapper(cls, obj):
        def convert(value):
            return cls(value) if type(value) is cls.wrapped_base else value
        def wrapper(*args, **kwargs):
            return convert(obj(*args, **kwargs))
        wrapper.__name__ = obj.__name__
        return wrapper

class Complex(complex):
    __metaclass__ = ReturnTypeWrapper
    wrapped_base = complex
    def __str__(self):
        return '({0}, {1})'.format(self.real, self.imag)
    def __repr__(self):
        return '{0}({1!r}, {2!r})'.format(self.__class__.__name__, 
                                          self.real, self.imag)


a = Complex(1+1j)
b = Complex(2+2j)

print type(a + b)

Note that this won't wrap the __coerce__ special method, since it returns a tuple of complexs; the wrapper can easily be converted to look inside sequences if necessary.

The __objclass__ attribute of unbound methods seems to be undocumented, but it points to the class the method is defined on, so I used it to filter out methods defined on classes other than the one we're converting from. I also use it here to filter out attributes that aren't unbound methods.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!