python - Why can't I invoke a static method inside the class body? - TagMerge
2Why can't I invoke a static method inside the class body?Why can't I invoke a static method inside the class body?

Why can't I invoke a static method inside the class body?

Asked 1 years ago
0
2 answers

Why can't I call the static function inside the class?

As said in the comments, class bodies are executed in Python. It is like a zero-argument function that automatically runs once; then invokes type, passing it the class name, bases and a dict of class attributes from the local variables of that function; and only then assigns the result from type (i.e., a class object) to the name.

You can even put logic and other statements in there:

import random

# a class that sometimes fails to exist when you import the module.
class spam:
    if __name__ != '__main__':
        1 / random.randrange(3)
    else:
        print("thank you for running this as the main script.")
    def __init__(self):
        # etc.

As such, names have to be in scope. At the time that this code is running - because it runs immediately and automatically, rather than being delayed like a function - there isn't a StaticClass until after this code has completed. Consequently, the code inside can't reference the class itself.

To solve this, simply move the call to the end:

class StaticClass(object):
    words = []
    
    @staticmethod
    def init(file_name):
        ...
        words.append('word')
        ...

    @staticmethod
    def fun():
        print('fun')

StaticClass.init()

Source: link

0

By the time the body of the StaticClass class is being executed there is no reference to StaticClass, it doesn't exist yet. The body of the class is executed inside a namespace which is a dictionary. After that a new instance of type type which is here named StaticClass is created using that populated dictionary and added to the global namespaces. That's what class keyword roughly does in simple form.

Actually I don't know why you want this to work. Others already suggested best ways to deal with it but here is workaround if you want to call staticmethod as an initializer function when the class is being created and call it inside the class:

class StaticClass(object):
    words = []

    @staticmethod
    def init(file_name, words=words):
        words.append(file_name)

    init.__get__(init)('word')

    @staticmethod
    def fun():
        print('fun')


test = StaticClass()
StaticClass.fun()
print(StaticClass.words)

output:

fun
['word']

Yes it's really a mess, I just want to make it work to say why it didn't work before. You need to call init.__get__ because staticmethods are not callable. (I'm in Python 3.9.7) This way you init executed when the class is created. Also words is not accessible because the scope of the class is not enclosed the scope of the body of init, so I use it's reference as default parameter.

Source: link

Recent Questions on python

    Programming Languages