28

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?

3
  • Nope. What are you trying to achive?
    – Martijn Pieters
    Jan 15, 2013 at 15:12
  • 1
    A class method takes the class as the first parameter because it uses the class. bar should be a @classmethod.
    – Katriel
    Jan 15, 2013 at 15:44
  • 1
    If the class is entirely static methods, maybe it could be refactored to a module with top-level functions that represent its public API. Then there is no prefixing to deal with, yet the functions are still grouped as a logical entity. Example: cpython/Lib/copy.py. Note that private functions on the module are prefixed with _ as normal.
    – ggorlen
    Sep 7, 2022 at 21:13

4 Answers 4

19

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.

1
  • 10
    Why make foo a classmethod when you're not using the class? I'd make foo a staticmethod and bar a classmethod (as you've done).
    – mgilson
    Jan 15, 2013 at 15:20
2

Not possible. It is a question of language design. Compare that to C++, where both this (the same as Python self; in Python you have to write self.var, in C++ you may write just var, not this->var) and own class are used by default in member functions, and you will probably see that sometimes that's good and sometimes that's annoying. The only thing possible is to get used to that feature.

0

You 'variable-ize' the class name. This will not remove, but shorten the name.

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

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

c = MyClass
-1

You can do something hacky by making a module level function foo and then adding it to the class namespace with staticmethod:

def foo():
    print "hi"

class MyClass(object):
    foo = staticmethod(foo)

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

    def baz(self):
        return foo()


c = MyClass()
c.bar()
c.baz()

MyClass.bar()
MyClass.foo()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.