/:“Primitive”和“list”的操作数类型不受支持

2024-04-18 23:10:33 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

这对py2有效,但对py3无效,这会引发一个错误:

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

除了这个错误,我还对原始语法obj/list感到困惑。
你们能帮我点个火吗?你知道吗


Tags: 项目key脚本value错误py3cmpython3
2条回答

很可能Primitive实现了__div__,允许它被另一个对象(在本例中是一个列表)“分割”。在python2中,x / y操作将使用x.__div__(y)(如果它不存在,则使用y.__rdiv__(x))。你知道吗

在python3中,这种行为已经改变了。要实现/除法运算符,需要实现__truediv__。这就解释了你所观察到的差异。你知道吗

大概您可以访问Primitive的源代码。只需将其__div__方法修补为__truediv__

这是由于python2和python3之间除法运算符的行为不同。你知道吗

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'

您需要为python3定义__truediv__特殊方法,而不是__div__。有关更多信息,请参见Python 2Python 3的数据模型。你知道吗

相关问题 更多 >