Search code examples
pythonclassself-reference

Python: How to refer a class inside itself?


Trying to refer a class inside itself. For e.g.

class Test:
    FOO_DICT = {1 : Test.bar}  # NameError: name 'Test' is not defined

    @staticmethod
    def bar():
        pass

Does this usage make sense? Any better alternatives? Thanks!


Solution

  • If you want the dictionary to be in the class: define the function first and remove Test:

    class Test:
        @staticmethod
        def bar():
             pass
    
        FOO_DICT = {1: bar}