Comments¶
- As long as the class name is not need at definition time of the class, it is OK to use it.
You cannot use a class in default values of the __init__
function of the class.
In [3]:
from __future__ import annotations
class MyClass1:
PI = 3.14
def __init__(self, value: float = MyClass1.PI):
pass
A simple way to fix the issue above is to give the default value None
to the argument
and parse it to the desired default value later inside in the __init__
function.
In [1]:
from __future__ import annotations
class MyClass1:
PI = 3.14
def __init__(self, value: float = None):
if value is None:
value = MyClass1.PI
After the import statement from __future__ import annotations
in Python 3.7+,
you can use a class name in type annotations in its own definition.
This is due to postponed evaluation of type annotation,
which essentially means that the the class name in type annotation
is not really needed at the its own definition time.
In [5]:
from __future__ import annotations
class MyClass2:
def __init__(self):
pass
def func(self) -> MyClass2:
pass
In [ ]:
In [ ]: