Python:从调用函数中获取值

标签 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缺乏了解,但我很难在这里找到明确的答案。最好的方法是将我想要的变量作为另一个第二个参数传递给第二个类吗? 如果有影响的话,它们位于单独的文件中。

最佳答案

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

是的,特别是如果对象之间只有短暂的关系:

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

关于Python:从调用函数中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53637963/

相关文章:

python - 我对这种消极的前瞻做错了什么?过滤掉正则表达式中的某些数字

python - 如何使用 GAE 让我的程序自动添加 cron 作业?

python - 日期与另一个表的开始日期和结束日期的左连接

python - argparse 参数模式

python - argparse:展平操作结果 ='append'

javascript - 如何将此 Python 标点符号去除功能转换为 JavaScript?

python - Cython:初始化结构化 Numpy 数组 ValueError

python - 在不使用 reshape 的情况下 reshape n 维数组的 View

python - 使用 OpenID 的 Pyramid 应用程序

python - wxpython:如何访问放置在 wx.Sizer 对象中的对象?