为什么调用 Python 的“魔术方法"不像对应的运算符那样进行类型转换?

Why does calling Python#39;s #39;magic method#39; not do type conversion like it would for the corresponding operator?(为什么调用 Python 的“魔术方法不像对应的运算符那样进行类型转换?)
本文介绍了为什么调用 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. 的情况下,它是float 的 __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__ 必须手动处理整数.如果您想在自己的运算符实现中进行类型转换,您也必须手动处理.

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 的“魔术方法"不像对应的运算符那样进行类型转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Multiprocessing on Windows breaks(Windows 上的多处理中断)
How to use a generator as an iterable with Multiprocessing map function(如何将生成器用作具有多处理映射功能的可迭代对象)
read multiple files using multiprocessing(使用多处理读取多个文件)
Why does importing module in #39;__main__#39; not allow multiprocessig to use module?(为什么在__main__中导入模块不允许multiprocessig使用模块?)
Trouble using a lock with multiprocessing.Pool: pickling error(使用带有 multiprocessing.Pool 的锁时遇到问题:酸洗错误)
Python sharing a dictionary between parallel processes(Python 在并行进程之间共享字典)