在python属性上重载运算符

编程入门 行业动态 更新时间:2024-10-19 12:45:59
本文介绍了在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属性上重载运算符

本文发布于:2023-06-03 12:19:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/473791.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:运算符   属性   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!