简体   繁体   中英

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.

It can be called that way within the class definition, eg 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).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM