Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

python - Using the class as a type hint for arguments in its methods


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Because when it encounters Translate (while compiling the class body), Vector2 hasn't been defined yet (it is currently compiling, name binding hasn't been performed); Python naturally complains.

Since this is such a common scenario (type-hinting a class in the body of that class), you should use a forward reference to it by enclosing it in quotes:

class Vector2:    
    # __init__ as defined

    def Translate(self, pos: 'Vector2'):    
        self.x += pos.x
        self.y += pos.y

Python (and any checkers complying to PEP 484) will understand your hint and register it appropriately. Python does recognize this when __annotations__ are accessed through typing.get_type_hints:

from typing import get_type_hints

get_type_hints(Vector2(1,2).Translate)
{'pos': __main__.Vector2}

This has been changed as of Python 3.7; see abarnert's answer below.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...