2024-04-18 23:10:33 发布
网友
我正在将一个项目(最初不是我的)从python2转换为python3。 在其中一个脚本中:
python2
python3
sk = (key.Sub[0]/["point", ["_CM"]]).value
这对py2,有效,但对py3无效,这会引发一个错误:
py2
py3
unsupported operand type(s) for /: 'Primitive' and 'list'
除了这个错误,我还对原始语法obj/list感到困惑。 你们能帮我点个火吗?你知道吗
obj/list
很可能Primitive实现了__div__,允许它被另一个对象(在本例中是一个列表)“分割”。在python2中,x / y操作将使用x.__div__(y)(如果它不存在,则使用y.__rdiv__(x))。你知道吗
Primitive
__div__
x / y
x.__div__(y)
y.__rdiv__(x)
在python3中,这种行为已经改变了。要实现/除法运算符,需要实现__truediv__。这就解释了你所观察到的差异。你知道吗
/
__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 2和Python 3的数据模型。你知道吗
很可能
Primitive
实现了__div__
,允许它被另一个对象(在本例中是一个列表)“分割”。在python2中,x / y
操作将使用x.__div__(y)
(如果它不存在,则使用y.__rdiv__(x)
)。你知道吗在python3中,这种行为已经改变了。要实现
/
除法运算符,需要实现__truediv__
。这就解释了你所观察到的差异。你知道吗大概您可以访问
Primitive
的源代码。只需将其__div__
方法修补为__truediv__
这是由于python2和python3之间除法运算符的行为不同。你知道吗
您需要为python3定义
__truediv__
特殊方法,而不是__div__
。有关更多信息,请参见Python 2和Python 3的数据模型。你知道吗相关问题 更多 >
编程相关推荐