gpt4 book ai didi

python -/: 'Primitive' and 'list' 不支持的操作数类型

转载 作者:太空宇宙 更新时间:2023-11-04 09:36:21 24 4
gpt4 key购买 nike

我正在将一个项目(不是我最初的项目)从 python2 转换为 python3
在我的一个脚本中:

sk = (key.Sub[0]/["point", ["_CM"]]).value

这适用于 py2但不适用于 py3,它会引发错误:

unsupported operand type(s) for /: 'Primitive' and 'list'  

除了错误,我还对原始语法 obj/list 感到困惑。
你们能在这里点一盏灯吗?

最佳答案

这是由于 Python 2 和 3 之间除法运算符的不同行为。

PS C:\Users\TigerhawkT3> py -2
Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> class A:
... def __div__(self, other):
... return 'call div'
... def __truediv__(self, other):
... return 'call truediv'
... def __floordiv__(self, other):
... return 'call floordiv'
...
>>> a = A()
>>> a/3
'call div'
>>> a//3
'call floordiv'
>>> exit()
PS C:\Users\TigerhawkT3> py
Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> class A:
... def __div__(self, other):
... return 'call div'
... def __truediv__(self, other):
... return 'call truediv'
... def __floordiv__(self, other):
... return 'call floordiv'
...
>>> a = A()
>>> a/3
'call truediv'
>>> a//3
'call floordiv'

您需要为 Python 3 定义 __truediv__ 特殊方法,而不是 __div__。请参阅 Python 2 的数据模型。和 Python 3了解更多信息。

关于python -/: 'Primitive' and 'list' 不支持的操作数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53575825/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com