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

   
  • 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). – CryptoFool Nov 03 '20 at 21:58
  • if you want access instance attribute in a static method ask yourself is it really static method :-) – buran Nov 03 '20 at 22:00
  • Does this answer your question? [Calling non-static method from static one in Python](https://stackoverflow.com/questions/1385546/calling-non-static-method-from-static-one-in-python) – PM 77-1 Nov 03 '20 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 – juanpa.arrivillaga Nov 03 '20 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. – Mark Ransom Nov 03 '20 at 22:05

1 Answers1

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!
CryptoFool
  • 21,719
  • 5
  • 26
  • 44