avenir
avenir

Reputation: 169

How can staticmethods be called as regular functions?

A static method can be called either on the class (such as C.f()) or on an instance (such as C().f()). Moreover, they can be called as regular functions (such as f()).

Could someone elaborate on the bold part of the extract from the documentation for Python static methods?

Reading this description one would expect to be able to do something like this:

class C:
    @staticmethod
    def f():
        print('f')
        
    def g(self):
        f()
        print('g')
        
C().g() 

But this generates:

NameError: name 'f' is not defined

My question is not about the use-cases where the static method call is name-qualified either with an instance or a class name. My question is about the correct interpretation of the bold part of the documentation.

Upvotes: 4

Views: 110

Answers (2)

avenir
avenir

Reputation: 169

The subsection 4.2.2. Resolution of names of the CPython documentation specifies the rules of visibility for variables defined in different type of nested code blocks. In particular it specifies the working of the visibility of the local class scope's variables inside its methods:

The scope of names defined in a class block is limited to the class block; it does not extend to the code blocks of methods

Upvotes: 1

Samwise
Samwise

Reputation: 71424

It can be called that way within the class definition, e.g. to initialize a class attribute:

class C:
    @staticmethod
    def f():
        print('f')
        return 42

    answer = f()

# f
print(C().answer)  # 42
print(C().answer)  # 42

Note that answer = f() is evaluated at the time the class is defined, not when an instance is constructed (so you see f printed only once).

Upvotes: 3

Related Questions