Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to self-reference a class in Python?

Tags:

python

I want this Template class to accept children of itself and other types with type(i) in self._allowed_types.

class Template():
    _allowed_types = [str, Template, SafeHtml]

Above code throws this:

NameError: name 'Template' is not defined
like image 201
Jesvin Jose Avatar asked Sep 19 '25 09:09

Jesvin Jose


1 Answers

Add the class after the class is defined:

class Template():
    _allowed_types = [str, SafeHtml]

Template._allowed_types.append(Template)

The class body, by necessity, is run before the class object can be created, so the name Template is not defined yet. But you can always alter class attributes after the object has been created.

like image 115
Martijn Pieters Avatar answered Sep 20 '25 22:09

Martijn Pieters