2016-11-02 11 views
0

私はPython3の型サポートの多くを使用し始めています。代わりのコンストラクタとして動作する戻り型のstaticmethodsに注釈を付けたいと思います。Python3で静的メソッドの戻り型に注釈を付ける

最小限の例を次に示します。私はそれが失敗したと注釈含まれている場合:

def from_other_datastructure(json_data: str) -> MyThing: 
    NameError: name 'MyThing' is not defined 
import typing 


class MyThing: 
    def __init__(self, items: typing.List[int]): 
     self.items = items 

    @staticmethod 
    def from_other_datastructure(json_data: str): 
     return MyThing(
      [int(d) for d in json_data.split(',')] 
     ) 

if __name__ == '__main__': 
    s1 = MyThing([1, 2, 3]) 

    s2 = MyThing.from_other_datastructure("2,3,4") 

を、それが型注釈のために定義されています前に、どのように1は、クラスを参照しますか?

答えて

1

私は正しい答えを見つけた。前方参照は文字列として定義することができる。

だから正解はかなり単純であり、ボーナスとしてPyCharmによってピックアップされています

@staticmethod 
def from_other_datastructure(json_data: str) -> 'MyThing': 
    return MyThing(
     [int(d) for d in json_data.split(',')] 
    ) 

https://www.python.org/dev/peps/pep-0484/#forward-references

関連する問題