[英]Most Pythonic way of setting user-friendly and explicit flag values?
What's the most Pythonic way of giving flags values that are user-friendly and self-evident for whoever is reading the code?为阅读代码的人提供用户友好且不言自明的标志值的最 Pythonic 方式是什么?
Assume I got the following method for a class, which depending on the input will calculate a certain multiplier
and set a cracking_mode
flag for that class instance:假设我为一个类获得了以下方法,该方法将根据输入计算某个multiplier
并为该类实例设置cracking_mode
标志:
def evaluate_first_matrix_crack(self, base_sigma22, base_tau12):
# Mixed transverse tension-shear
if base_sigma22 > 0 and base_tau12 != 0:
self.cracking_mode = 2
multiplier = sqrt(1. / ((base_sigma22 / self.Yt_is) ** 2 + (base_tau12 / self.S_is) ** 2))
# Pure transverse tension
elif base_sigma22 > 0 and base_tau12 == 0:
self.cracking_mode = 0
multiplier = self.Yt_is / base_sigma22
# Pure shear
elif base_sigma22 <= 0 and base_tau12 != 0:
self.cracking_mode = 1
multiplier = self.Yt_is / base_sigma22
return multiplier
The "cracking_mode" flag will affect which methods are called in other sections of the code. “cracking_mode”标志将影响在代码的其他部分调用哪些方法。 I want the flag values to be as user-friendly as possible, so that when they are checked through if statements in other sections of the code, the reader can immediately tell which flag value corresponds to which option.我希望标志值尽可能对用户友好,以便在通过代码的其他部分中的 if 语句检查它们时,读者可以立即知道哪个标志值对应于哪个选项。
So rather than having self.cracking_mode = 2
I would ideally have self.cracking_mode = "mixed_transverse_tension_shear"
.因此,与其拥有self.cracking_mode = 2
不如让我拥有self.cracking_mode = "mixed_transverse_tension_shear"
。
However, I don't think that's a Pythonic way of doing things, aside from the fact that comparing strings takes longer than comparing integers.但是,我认为这不是 Pythonic 的做事方式,除了比较字符串比比较整数花费的时间更长的事实。
So what would be the most Pythonic (and user-friendly) way of solving the issue?那么解决这个问题的最 Pythonic(和用户友好)的方法是什么?
This is exactly the purpose of enum
in other languages.这正是enum
在其他语言中的目的。 In my opinion, the most "pythonic" way to do things is simply the clearest - so string comparison isn't that bad.在我看来,最“pythonic”的做事方式就是最清晰的——所以字符串比较并没有那么糟糕。 Probably a little better would be to create constants that represent the values ( MIXED_TRANVERSE_TENSION_SHEAR = 2
) as static class members, and then compare to those constants, which is a more efficent integer comparison.创建将值( MIXED_TRANVERSE_TENSION_SHEAR = 2
)表示为静态类成员的常量,然后与这些常量进行比较,这是一种更有效的整数比较,可能会更好一些。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.