简体   繁体   中英

how to access a python method within a class from a staticmethod within the same class

I need to execute a method from a @staticmethod within the same class: the following code returns an error:

NameError: global name 'self' is not defined

class Main:
    def __init__(self):
        self.start = 0

    def prints(self, message):
        print (message)

    @staticmethod
    def sendMessage(message):
        self.prints(message)

if __name__ == '__main__':
    main = Main()
    main.sendMessage('Testing to print from staticmethod')

could someone give me an idea, how to access the prints methods from the statimethod. thank you

You can't access not static class members from a static method. Static means, that you do not need to generate an instance of the class. Therefore you could use static methods without having an object of the class. Without having an object the non-static member function is never generated and therefore you can't call it. There exists no self in a static scope.

You would have to make your prints(message) method static as well to access it

If you are doing like this, then you need to initiate class inside of static method and pass the variable you want to print or other stuf. There is no other way for it.

@staticmethod
def sendMessage(message):
    Main.prints(None, message) # Prefixing with Main so prints can be found.

When a static method is called, the caller doesn't pass itself (also, the caller won't be an instance of the class). This is why self is not defined in your code.

To reference prints, use Main.prints . And to call it, fit the argument list: when prints is called statically, there is no instance reference to pass as the self argument, so explicitly passing something else ( None in my example) forces it to work.

This will make the code run, but you probably be mixing static and non-static methods like this. Also, in your code, sendMessage is being called from an instance. To call it statically would look like: Main.sendMessage('...') .

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