Ben Chuanlong Du's Blog

It is never too late to learn.

Use a Class in the Definition of the Class in Python

Comments

  1. 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
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-3-25d31772944c> in <module>
      2 
      3 
----> 4 class MyClass1:
      5     PI = 3.14
      6 

<ipython-input-3-25d31772944c> in MyClass1()
      5     PI = 3.14
      6 
----> 7     def __init__(self, value: float = MyClass1.PI):
      8         pass

NameError: name 'MyClass1' is not defined

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 [ ]:

Comments