代码之家  ›  专栏  ›  技术社区  ›  Pedro Lobito

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

  •  0
  • Pedro Lobito  · 技术社区  · 6 年前

    我正在将一个项目(不是我的)从 python2 python3 .
    在其中一个脚本中,我有:

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

    这工作在 py2 ,请 但不是 py3 ,引发错误:

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

    除了错误,我还对原始语法感到困惑 obj/list .
    你们能在这里放光吗?

    2 回复  |  直到 6 年前
        1
  •  2
  •   TigerhawkT3    6 年前

    这是因为python 2和3之间的division操作符的行为不同。

    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'
    

    您需要定义 __truediv__ 特殊方法,而不是 __div__ ,对于python 3。参见数据模型 Python 2 Python 3 更多信息。

        2
  •  2
  •   donkopotamus    6 年前

    很可能 Primitive 器具 __div__ 允许它被另一个对象(本例中的列表)分割。在python 2中,操作 x / y 将使用 x.__div__(y) 如果它存在(如果它不存在,那么 y.__rdiv__(x) .

    在Python3中,这种行为 改变 .执行 / 需要实现的除法运算符 __truediv__ . 这就解释了你所观察到的差异。

    你大概可以访问 本原 . 只需修补 第二代 方法 TyeDeVixy