2

so I have a question regarding passing class instances around. I am aware that this is not at all the most optimal approach to the problem and a number of workarounds can be used, I am more curious to know if this is even possible at all.

So lets say I have a function function (defined outside of the class) expecting a class instance as input to be able to run:

def function(class_instance):
    # Do something using/modifying the passed class_instance's properties
    return

Is it possible to call this function from inside a class method (here run_function) and pass to it the whole instance it is called from (so from within the class instance itself)?

class:
    def run_function(self):
        function(???class_instance???)    # Somehow pass the class instance current?
        return


class_instance = class()
class_instance.run_function()

Again I am aware that here the function could be simply inserted in as the method itself, or that I could re-write the function to expect the required properties as input and then pass the self. properties in the method definition, or even that I could add the class_instance as an input of the method run_function and then pass the class_instance when the method is called. I am however wondering if there is a solution to this problem in this specific configuration.

Sorry if the example/question is unclear, but this is the best and simplest example I could think of to illustrate my issue. Cheers!

newacct
  • 119,665
  • 29
  • 163
  • 224
  • 1
    `function(self)`? Not sure if that's what you're looking for. `self` is the current instance. – Carcigenicate Feb 15 '20 at 15:14
  • 1
    The first parameter for all instance methods in a class is always the instance itself, idiomatically named - `self` – Tomerikoo Feb 15 '20 at 15:16
  • Does this answer your question? [Passing an instance of a class (object of a class) to another class](https://stackoverflow.com/questions/24223722/passing-an-instance-of-a-class-object-of-a-class-to-another-class) – A.Casanova Apr 22 '23 at 11:01

0 Answers0