在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/