简体   繁体   English

从 function 返回大量变量的优雅方式

[英]Elegant way to return lot of variables from a function

I have a python method of a class which is calculating a bunch of stuff, stores them in 8 different variables and then want to return these values.我有一个 class 的 python 方法,它正在计算一堆东西,将它们存储在 8 个不同的变量中,然后想要返回这些值。

Something on the lines;线上的东西;

def rate_lookup(self, a):
   ....
   ....

   return(charge, 
              handling_charge,
              delivery_charge,
              fuel_surcharge,
              overheight_surcharge,
              security_charge,
              documentation_fee,
              unpacking_removal_fee)

Problem is I would then have to save these return values in anothe similar set of variables on the function call.问题是我必须将这些返回值保存在 function 调用上的另一组类似变量中。 That doesn't look very elegant and uses a lot of variables.这看起来不是很优雅,并且使用了很多变量。

I do need each variables value as I need to later print them out to console based on certain criteria.我确实需要每个变量值,因为我需要稍后根据某些标准将它们打印到控制台。

Whats the best way to retun a lot of variables value.什么是重新调整大量变量值的最佳方法。

IMO, this usually means your function is doing too much you might want to break it down to several functions or a Class. IMO,这通常意味着您的 function做得太多,您可能想将其分解为几个功能或 Class。 if you still decide you want to use a single function, I'd suggest using a namedtuple to return you values in a manner you could refer to them by name.如果您仍然决定要使用单个function ,我建议使用命名元组以您可以按名称引用它们的方式返回值。

You need a dataclass.你需要一个数据类。 Pick one which suits best for you:选择一个最适合您的:

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

相关问题 Python,如何以最优雅的方式将任意变量从 function 传递给 function? - Python, how to pass arbitrary variables from function to function in the most elegant way? 从函数返回多个值的优雅方法 - Elegant ways to return multiple values from a function Python - 从可能返回None的函数设置变量的安全而优雅的方法 - Python - safe & elegant way to set a variable from function that may return None Python:结合函数多次运行的输出变量的优雅方法 - Python: Elegant way to combine output variables of a function run many times 从 Python 中的局部变量创建 dict 的优雅方式 - Elegant way to create dict from local variables in Python 从列表中分配变量,或“如何制作优雅的保存功能” - Assigning variables from a list, or “how to make an elegant save function” 一种检查长变量列表中是否有一个不是“ None”并返回不存在的变量的优雅方法? - Elegant way to check if any of long list of variables is not None, and return the one that isn't? 从 python 函数分配可变数量的返回值的优雅方法 - Elegant way to assign a variable number of returns from a python function 在C中,从函数返回2个变量 - In C, return 2 variables from a function “Pythonic”/更优雅的方式将多个变量设置为相同的函数调用或列表理解 - "Pythonic"/more elegant way to set multiple variables to the same function call or list comprehension
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM