Luca
Luca

Reputation: 1810

Is it possible to call a static method from withing another static method

Is it possible to call a static method from within another static method?

I tried this:

class MyClass(object):

    @staticmethod
    def static_method_1(x):
        x = static_method_2(x)
        print x

    @staticmethod
    def static_method_2(x):
        return 2*x

This returns

NameError: name 'static_method_2' is not defined

Upvotes: 3

Views: 232

Answers (2)

chepner
chepner

Reputation: 530940

A static method must be invoked via the class that defines it; otherwise, that's just about the only difference between it and a regular function.

@staticmethod
def static_method_1(x):
    x = MyClass.static_method_2(x)
    print x

The reason is that the name static_method_2 isn't defined in the global scope, or in any other non-local scope (remember, a class does not define a new scope). The static method is simply an attribute of MyClass, and has to be accessed as such.

Upvotes: 2

Daniel Roseman
Daniel Roseman

Reputation: 599490

Staticmethods are called via the class: MyClass.static_method_2(x).

You probably don't want a staticmethod at all, but a classmethod. These are called the same way but get a reference to the class, which you can then use to call the other method.

class MyClass(object):

    @classmethod
    def static_method_1(cls, x):
        x = cls.static_method_2(x)
        print x

    @classmethod
    def static_method_2(cls, x):
        return 2*x

Note, in Python you wouldn't ever do this. There's usually no reason to have a class unless it is storing state. These would probably both be best as standalone functions.

Upvotes: 7

Related Questions