Python:从调用函数中获取值
在Python中,调用的函数是否有一种简单的方法从调用的函数/类中获取值?我不确定我的措辞是否正确,但我正在尝试这样做:Python:从调用函数中获取值,python,Python,在Python中,调用的函数是否有一种简单的方法从调用的函数/类中获取值?我不确定我的措辞是否正确,但我正在尝试这样做: class MainSection(object): def function(self): self.var = 47 # arbitrary variable self.secondaryObject = secondClass() # Create object of second class self.se
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
及
这可能是我对Python缺乏了解,但我很难在这里找到一个明确的答案。最好的方法是将我想要的变量作为第二个参数传递给第二个类吗?
如果有区别的话,这些都在单独的文件中
最好的方法是将我想要的变量作为第二个参数传递给第二个类吗
是的,尤其是当对象之间只有短暂关系时:
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
您试图从第二个函数访问
self.var
的确切位置?你可以通过Self.var来调用它:<代码> SudialObjult.Sudio函数(So.Var)< /Cord>好答案,也可以考虑从我的评论中添加我的例子。同意他问的和你说的well@Jaba当然,我也添加了一个传递变量的示例。谢谢你的反馈。
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