Search code examples
pythoninitializationstatic-methods

staticmethod not available when init runs


I realised that I cannot call a class' static method from its __init__ method.

class c():

    def __init__(self):
        f()

    @staticmethod
    def f():
        print("f called")

c()

gives a NameError: name 'f' is not defined.

Why is it not able to find the static method?


Solution

  • This is simply because Python is searching for a function called f in the global namespace when you reference it like that.

    To reference the class' f method, you need to make sure Python is looking in the appropriate namespace. Just prepend a self..

    class c():
    
        def __init__(self):
            self.f()  # <-
    
        @staticmethod
        def f():
            print("f called")
    
    c()
    

    results in

    f called