【问题标题】:unsupported operand type(s) for /: 'Primitive' and 'list'/ 不支持的操作数类型:“原始”和“列表”
【发布时间】:2018-12-01 23:03:17
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 但是为什么它在py2而不是py3上工作,这种操作的语法改变了吗?
  • / 运算符在 Python 2 和 3 之间的行为不同;这可能是问题所在。
  • @TigerhawkT3 / 中的哪些行为从 py2 更改为 py3?你介意开发它吗?

标签: python python-3.x python-2.x


【解决方案1】:

这是由于 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 2Python 3 的数据模型。

【讨论】:

  • 你的例子帮助我解决了这个问题。谢谢!
【解决方案2】:

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

在 Python 3 中,此行为已更改。要实现/ 除法运算符,您需要实现__truediv__。这解释了您观察到的差异。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-23
    • 1970-01-01
    • 2018-02-21
    • 2015-11-23
    • 1970-01-01
    • 2021-08-17
    相关资源
    最近更新 更多