我有一堂课,如下所示
class ExperimentResult(BaseDataObject):
def __init__(self, result_type: str, data: dict, references: list):
super().__init__()
self.type = result_type
self.references = references
self.data = data
def __repr__(self):
return str(self.__dict__)
代码是用 python 3 编写的,而我尝试在 python 2 中运行它。 当我运行它时,我得到
def __init__(self, result_type: str, data: dict, references: list):
^
SyntaxError: invalid syntax
有“import_from_future”来解决这个问题吗?
不,没有
__future__
开关可以在 Python 2 中启用 Python 3 注释。如果您使用注释进行类型提示,请改用注释。
请参阅 PEP 484 的Python 2.7 和跨式代码的建议语法部分以及类型检查 Python 2 代码部分了解语法详细信息:
对于需要兼容Python 2.7的代码,函数类型注释在注释中给出,因为函数注释语法是在Python 3中引入的。
对于您的具体示例,那就是:
class ExperimentResult(BaseDataObject):
def __init__(self, result_type, data, references):
# type: (str, dict, list) -> None
super().__init__()
self.type = result_type
self.references = references
self.data = data