为什么调用Python的“魔术方法"不会像对相应的运算符那样进行类型转换? [英] Why does calling Python's 'magic method' not do type conversion like it would for the corresponding operator?

查看:76
本文介绍了为什么调用Python的“魔术方法"不会像对相应的运算符那样进行类型转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我从整数中减去浮点数时(例如1-2.0),Python会进行隐式类型转换(我认为).但是,当我使用魔术方法__sub__调用我认为是相同的操作时,它突然消失了.

When I subtract a float from an integer (e.g. 1-2.0), Python does implicit type conversion (I think). But when I call what I thought was the same operation using the magic method __sub__, it suddenly does not anymore.

我在这里想念什么?当我为自己的类重载运算符时,除了将输入显式转换为所需的任何类型之外,还有其他方法吗?

What am I missing here? When I overload operators for my own classes, is there a way around this other than explicitly casting input to whatever type I need?

a=1
a.__sub__(2.)
# returns NotImplemented
a.__rsub__(2.)
# returns NotImplemented
# yet, of course:
a-2.
# returns -1.0

推荐答案

a - b不仅仅是a.__sub__(b).如果a无法处理该操作,它还会尝试b.__rsub__(a),在1 - 2.情况下,浮点数的__rsub__可以处理该操作.

a - b isn't just a.__sub__(b). It also tries b.__rsub__(a) if a can't handle the operation, and in the 1 - 2. case, it's the float's __rsub__ that handles the operation.

>>> (2.).__rsub__(1)
-1.0

您运行了a.__rsub__(2.),但这是错误的__rsub__.您需要右侧操作数的__rsub__,而不是左侧操作数.

You ran a.__rsub__(2.), but that's the wrong __rsub__. You need the right-side operand's __rsub__, not the left-side operand.

减法运算符没有内置隐式类型转换. float.__rsub__必须手动处理int.如果要在自己的运算符实现中进行类型转换,则也必须手动处理.

There is no implicit type conversion built into the subtraction operator. float.__rsub__ has to handle ints manually. If you want type conversion in your own operator implementations, you'll have to handle that manually too.

这篇关于为什么调用Python的“魔术方法"不会像对相应的运算符那样进行类型转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆