How to call static method from inside of a class body?

Viewed 4468

Let's assume I have a class, with a static method, and I want a class property to be set to the value that this method returns:

class A:
    @staticmethod
    def foo():
        return 12

     baz = foo()

But doing this I get an error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in A
TypeError: 'staticmethod' object is not callable

I found a way to get around this:

class A:
    class B:
        @staticmethod
        def foo():
            return 2
baz = B.foo()

But for example if I write:

class A:
    class B:
        @staticmethod
        def foo():
            return 2

    class C:
        baz = B.foo()

I also get an error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in A
  File "<stdin>", line 7, in C
NameError: name 'B' is not defined

Is there a way to call static methods from within a class while declaring it? Why 1st and 3rd examples of code does not work but 2nd does? How python interpretor handles such declarations?

2 Answers
Related