如何为自定义类的参数指定Type Hint?

bra*_*ran 1 python types function type-hinting python-3.x

假设我创建了一个下面定义的类,并在其上调用了方法:

class Student:

    def __init__(self, name):
        self.name = name
        self.friends = []

    def add_friend(self, new_friend: Student):
        self.friends.append(new_friend)

student1 = Student("Brian")
student2 = Student("Kate")
student1.add_friend(student2)
Run Code Online (Sandbox Code Playgroud)

该方法add_friend有一个称为的参数new_friend,它是一个Student对象。如何使用类型提示进行指定?我假设您只需要简单地输入类的名称即可,new_friend: Student但这是行不通的。运行它时,我得到一个NameError: name 'Student' is not defined。我也尝试过new_friend: __main__.Student,但这给了我同样的错误。我究竟做错了什么?

unu*_*tbu 5

根据PEP-484,将类的字符串名称用于正向引用:

class Student:

    def __init__(self, name):
        self.name = name
        self.friends = []

    def add_friend(self, new_friend: 'Student'):
        self.friends.append(new_friend)
Run Code Online (Sandbox Code Playgroud)