有没有办法为不同版本的python定义不同的函数(具有相同的主体)?
具体来说,对于 python 2.7 定义:
def __unicode__(self):
对于 python 3 定义:
def __str__(self):
但两者都将具有相同的代码/正文。两者都必须是类的成员。
有没有办法为不同版本的python定义不同的函数(具有相同的主体)?
具体来说,对于 python 2.7 定义:
def __unicode__(self):
对于 python 3 定义:
def __str__(self):
但两者都将具有相同的代码/正文。两者都必须是类的成员。
第三方six
库定义了一个python_2_unicode_compatible
类装饰器,它接受一个带有__str__
方法的类并将其转换为__unicode__
Python 2。
虽然有兼容性库;作为最广为人知的 2 个,有时需要在没有兼容性库的情况下生活six
。future
您总是可以编写自己的类装饰器,并将其放入 saymypackage/compat.py
中。以下内容非常适合以 Python 3 格式编写类,并在需要时将 3-ready 类转换为 Python 2(同样可用于next
vs__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!'
(注意我们使用的是 u'' 前缀,它是 PyPy 3 和 Python 3.3+ 兼容的,所以如果你需要兼容 Python 3.2,那么你需要做相应的调整)
要在 Python 2 中提供将 UTF-8__str__
编码为 UTF-8 的方法,您可以将__unicode__
del cls.__str__
def __str__(self):
return unicode(self).encode('UTF-8')
cls.__str__ = __str__