簡體   English   中英

運行python 3代碼時python 2語法錯誤

[英]python 2 syntax error when running python 3 code

我有一堂課,看起來像下面這樣

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 2中運行時,代碼是用python 3編寫的。運行時,我得到了

    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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM