Let's say that I have created a class defined below, and I 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 a parameter called new_friend, which is a Student object. How do I use type hints to specify that? I assumed that you just have to simply enter the name of the class, like new_friend: Student but it does not work. When I run it, I get a NameError: name 'Student' is not defined. I also tried new_friend: __main__.Student, but it gives me the same error. What am I doing wrong?
Per PEP-484, use the string name of the class for 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With