1

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

   
5
  • 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. Until you create an instance of the class, there's no way to call an instance method (hence the name). Commented Nov 3, 2020 at 21:58
  • if you want access instance attribute in a static method ask yourself is it really static method :-) Commented Nov 3, 2020 at 22:00
  • Does this answer your question? Calling non-static method from static one in Python Commented Nov 3, 2020 at 22:00
  • If you have a static method that needs to access an instance method, it shouldn't be a static method. Just make it an instance method. The whole point of a static method is that it doesnt need to access attributes*. If it does then it shouldn't be static Commented Nov 3, 2020 at 22:01
  • If instance_method doesn't actually need any attributes from an instance, just declare it static too. Then calling it won't be a problem. Commented Nov 3, 2020 at 22:05

1 Answer 1

0

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!
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.