小编bra*_*ran的帖子

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

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

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,但这给了我同样的错误。我究竟做错了什么?

python types function type-hinting python-3.x

1
推荐指数
1
解决办法
1601
查看次数

标签 统计

function ×1

python ×1

python-3.x ×1

type-hinting ×1

types ×1