4

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.

1
  • I would guess that it implicitly means "…where f is in scope." E.g. you could call f() within the class definition. Commented Dec 11, 2022 at 15:46

2 Answers 2

3

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).

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.