python - How to specify Type Hint for Parameters for Custom Classes? -
this question has answer here:
let's have created class defined below, , have called methods on it:
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) the method add_friend has parameter called new_friend, student object. how use type hints specify that? assumed have enter name of class, new_friend: student not work. when run it, nameerror: name 'student' not defined. tried new_friend: __main__.student, gives me same error. doing wrong?
per pep-484, use string name of class forward references:
class student: def __init__(self, name): self.name = name self.friends = [] def add_friend(self, new_friend: 'student'): self.friends.append(new_friend)
Comments
Post a Comment