Home >Backend Development >Python Tutorial >How Can I Properly Handle Type Hints for Enclosed Classes in Python?
Understanding the Issue
When defining a method that refers to the enclosing class as its return type, you may encounter an unresolved reference error. Let's consider the following code in Python 3:
This code fails with a NameError because the Position class is not defined within the scope of the __add__ method.
Resolving the Issue
Python 3.11 with 'Self' Type:
In Python 3.11 and later versions, you can use the Self type to reference the enclosing class within type hints:
Python 3.7 with '__future__ import annotations':
If you're using Python 3.7 or newer, you can enable the postponed evaluation of annotations by adding the following import statement:
With this enabled, the type hints will be stored as strings until the module is fully loaded, resolving the reference issue:
Python <3.7:
For Python versions below 3.7, you can specify a string reference to the enclosing class using single quotes:
This creates a forward reference that will be resolved once the class is defined.
Additional Notes:
The above is the detailed content of How Can I Properly Handle Type Hints for Enclosed Classes in Python?. For more information, please follow other related articles on the PHP Chinese website!