bugmenot123
bugmenot123

Reputation: 1145

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?

Upvotes: 0

Views: 476

Answers (2)

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20500

Since f() is a method of the class, you can either use c.f() or self.f() to call it

class c():

    def __init__(self):
        #Call static method using classname
        c.f()
        #Call static method using self
        self.f()

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

c()

Then the output will be

f called
f called

Similarly to call static method outside the class, we can use ClassName or Instance

#Using classname to call f
c.f()

#Using instance to call f
c().f()

The output will be

f called
f called

Upvotes: 0

bugmenot123
bugmenot123

Reputation: 1145

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

Upvotes: 2

Related Questions