Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: possible to call static method from within class without qualifying the name

This is annoying:

class MyClass:
    @staticmethod
    def foo():
        print "hi"

    @staticmethod
    def bar():
        MyClass.foo()

Is there a way to make this work without naming MyClass in the call? i.e. so I can just say foo() on the last line?

like image 330
Sideshow Bob Avatar asked Sep 05 '25 03:09

Sideshow Bob


1 Answers

There is no way to use foo and get what you want. There is no implicit class scope, so foo is either a local or a global, neither of which you want.

You might find classmethods more useful:

class MyClass:
    @classmethod
    def foo(cls):
        print "hi"

    @classmethod
    def bar(cls):
        cls.foo()

This way, at least you don't have to repeat the name of the class.

like image 87
Ned Batchelder Avatar answered Sep 07 '25 21:09

Ned Batchelder