简体   繁体   中英

Python: Getting value from calling function

In Python, is there a simple way for an invoked function to get a value from the calling function/class ? I'm not sure if I'm phrasing that right, but I'm trying to do something like this:

class MainSection(object):
    def function(self):
        self.var = 47  # arbitrary variable 
        self.secondaryObject = secondClass()  # Create object of second class
        self.secondaryObject.secondFunction(3)  # call function in that object

and

class secondClass(object):
    def secondFunction(self, input)
        output = input + self.var  # calculate value based on function parameter AND variable from calling function
        return output
        #Access self.var from MainSection

This might be my lack of knowledge about Python, but I'm having a hard time finding a clear answer here. Is the best way to do that just passing the variable I want in as another second parameter to the second class? These are in separate files, if that makes a difference.

Is the best way to do that just passing the variable I want in as another second parameter to the second class?

Yes, especially if there's only a transient relationship between the objects:

class secondClass(object):
    def secondFunction(self, input, var_from_caller)
        output = input + var_from_caller  # calculate value based on function parameter AND variable from calling function
        return output

You can even pass around the whole object if you like:

class secondClass(object):
    def secondFunction(self, input, calling_object)
        output = input + calling_object.var  # calculate value based on function parameter AND variable from calling function
        return output

If the relationship is more permanent, you could consider storing references to the related objects in instance variables:

class MainSection(object):
    def function(self):
        self.var = 47  # arbitrary variable 
        self.secondaryObject = secondClass(self)  # Create object of second class
        self.secondaryObject.secondFunction(3)  # call function in that object

...
class secondClass(object):
    def __init__(self, my_friend):
        self.related_object = my_friend

    def secondFunction(self, input)
        output = input + self.related_object.var  # calculate value based on function parameter AND variable from calling function
        return output
        #Access self.var from MainSection

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