简体   繁体   中英

Calling an instance method within a static method in Python

Lets say I have class with a static and instance method. How would I go about calling the instance method from my static method: I wouldn't be able to use self in the static method. So, would it look something like this?

class Example():
    def instance_method(self):
         pass
    @staticmethod
    def static_method():
         instance_method()
  
    

   

Calling a non-static method in a class requires that an object exists of that class, and that you have a reference to that object. You could have 100s of instances of the same class, all of which could behave differently when one of that class's instance methods is called on them. Until you create an instance of the class, there's no way to call an instance method (hence the name).

Here's a trivial answer to your question, which is to create an instance of the class just so you can call the method you're interested in calling:

class Example():

    def instance_method(self):
        print("I'm an instance method!")

    @staticmethod
    def static_method():
        instance = Example()
        instance.instance_method()

Example.static_method()

Result:

I'm an instance method!

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