azu*_*r88 1 python multiple-versions
有没有办法为不同版本的python定义不同的函数(具有相同的主体)?
具体来说,对于 python 2.7 定义:
def __unicode__(self):
Run Code Online (Sandbox Code Playgroud)
对于 python 3 定义:
def __str__(self):
Run Code Online (Sandbox Code Playgroud)
但两者都有相同的代码/主体。两者都必须是班级成员。
虽然有兼容性库;six作为future最广为人知的两个,有时人们需要在没有兼容性库的情况下生活。您始终可以编写自己的类装饰器,并将其放入 say 中mypackage/compat.py。以下内容非常适合以 Python 3 格式编写类,并在需要时将 3-ready 类转换为 Python 2(同样可以用于nextvs__next__等:
import sys
if sys.version_info[0] < 3:
def py2_compat(cls):
if hasattr(cls, '__str__'):
cls.__unicode__ = cls.__str__
del cls.__str__
# or optionally supply an str that
# encodes the output of cls.__unicode__
return cls
else:
def py2_compat(cls):
return cls
@py2_compat
class MyPython3Class(object):
def __str__(self):
return u'Here I am!'
Run Code Online (Sandbox Code Playgroud)
(请注意,我们使用的 u'' 前缀仅与 PyPy 3 和 Python 3.3+ 兼容,因此如果需要兼容 Python 3.2,则需要进行相应调整)
要在 Python 2 中提供__str__将 编码为 UTF-8 的方法,您可以将 替换为__unicode__del cls.__str__
def __str__(self):
return unicode(self).encode('UTF-8')
cls.__str__ = __str__
Run Code Online (Sandbox Code Playgroud)