本文介绍了在python属性上重载运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以在python属性上重载运算符?像这样:
Is it possible to overload an operator on a python property? Something like:
class Foo( object ): @property def bar( self ): return unfoobar( self._bar ) @bar.setter def bar( self, baz ): self._bar = foobar( baz ) @bar.__eq__ def bar( self, baz ): return self._bar == foobar( baz )没有为_bar定义特殊的类(尽管在此示例中,这可能是最好的解决方案……).
without defining a special class for _bar (although in this example, that's probably the best solution...).
推荐答案否,运算符将应用于属性的 value (由属性提供或从__dict__映射获取)或广告位),而不是属性本身.
No, operators are applied to the value of an attribute (be it supplied by a property or taken from the __dict__ mapping or a slot), never the attribute itself.
恐怕您将必须返回实现__eq__的特殊包装并将其返回.
You will have to return a special wrapper implementing __eq__ and return that, I am afraid.
更多推荐
在python属性上重载运算符
发布评论