简体   繁体   English

将变量从一个函数传递到另一个函数

[英]Passing a variable from one function to another function

I have a function with way to much going on in it so I've decided to split it up into smaller functions and call all my block functions inside a single function. 我的函数尚有很多工作要做,因此我决定将其拆分为较小的函数,并在一个函数中调用所有块函数。 --> eg ->例如

def main_function(self):
  time_subtraction(self)
  pay_calculation(self,todays_hours)

and --> 和->

def time_subtraction(self):
    todays_hours = datetime.combine(datetime(1,1,1,0,0,0), single_object2) - datetime.combine(datetime(1,1,1,0,0,0),single_object)
    return todays_hours

So what im trying to accomplish here is to make todays_hours available to my main_function . 因此,我要在这里完成的工作是让todays_hours可以使用main_function I've read lots of documentation and other resources but apparently I'm still struggling with this aspect. 我已经阅读了许多文档和其他资源,但显然我仍然在这方面苦苦挣扎。

EDIT -- This is not a method of the class. 编辑 -这不是该类的方法。 Its just a file where i have a lot of functions coded and i import it where needed. 它只是一个文件,我在其中编码了许多功能,并在需要时将其导入。

If you want to pass the return value of one function to another, you need to either nest the function calls: 如果要将一个函数的返回值传递给另一个函数,则需要嵌套该函数调用:

pay_calculation(self, time_subtraction(self))

… or store the value so you can pass it: …或存储值,以便您可以传递它:

hours = time_subtraction(self)
pay_calculation(self, hours)

As a side note, if these are methods in a class, you should be calling them as self.time_subtraction() , self.pay_calculation(hours) , etc., not time_subtraction(self) , etc. And if they aren't methods in a class, maybe they should be. 附带说明一下,如果这些是类中的方法,则应将它们称为self.time_subtraction()self.pay_calculation(hours)等,而不是time_subtraction(self)等。并且如果它们不是方法在课堂上,也许他们应该是。

Often it makes sense for a function to take a Spam instance, and for a method of Spam to send self as the first argument, in which case this is all fine. 通常,对于一个函数来说,接受一个Spam实例,然后让一个Spam方法将self作为第一个参数发送,在这种情况下,这一切都很好。 But the fact that you've defined def time_subtraction(self): implies that's not what's going on here, and you're confused about methods vs. normal functions. 但是,您定义了def time_subtraction(self):的事实意味着这不是这里要发生的事情,并且您对方法与常规函数感到困惑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM