[英]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:
选择一个最适合您的:
__slots__
__slots__
的定制 class
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.