我知道您可以使用元类将运算符重载为classmethods:
class _Two(type):
def __add__(self, other):
return (2 + other)
class Two(object):
__metaclass__ = _Two
Two + 3 # 5
它适用于Python 2.7.6但在3.4.0中失败并出现此错误:
TypeError: unsupported operand type(s) for +: 'type' and 'int'
为什么?
你可以用兼容这两个版本的方式来做到这一点:
class _Two(type):
def __add__(self, other):
return (2 + other)
class Two(_Two('', (object,), {})): pass
Two + 3 # 5
我知道为什么第二个版本有效,但在我看来它与第一个版本基本相同,所以我错过了什么?
答案 0 :(得分:3)
在Python3中使用元类的正确方法是:
class Two(metaclass=_Two):
...
也就是说,在Python3中添加__metaclass__
作为类属性没有什么特别之处。你得到了同样的错误,如果你写了:
>>> class Two(object):
this_does_nothing_special = _Two
>>> Two + 3
TypeError: unsupported operand type(s) for +: 'type' and 'int'