Python:从调用函数中获取价值

时间:2018-12-05 17:44:19

标签: python

在Python中,被调用函数是否有一种简单的方法来从调用函数/类中获取值?我不确定是否要这样说,但我正在尝试执行以下操作:

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

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

这可能是我对Python缺乏了解,但是我很难在这里找到明确的答案。做到这一点的最佳方法就是将我想要的变量作为另一个第二个参数传递给第二个类吗? 这些文件在单独的文件中,如果有区别的话。

1 个答案:

答案 0 :(得分:2)

  

做到这一点的最佳方法是将我想要的变量作为另一个第二个参数传递给第二个类吗?

是的,尤其是在对象之间只有短暂关系的情况下:

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

如果愿意,甚至可以绕过整个对象

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

如果该关系更持久,则可以考虑将对相关对象的引用存储在实例变量中:

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