Python变量命名约定
所以我试图切换到 PEP8 表示法(从相当个人化的 CamelCase 表示法),我想知道你们如何处理现有函数/变量将被覆盖的情况?
例如,有类似的东西:
open, high, low, close, sum = row
已经覆盖了“open”和“sum”函数。 首先,如果我不使用好的 IDE,我什至不会注意到我刚刚覆盖了重要的基本功能。其次,您将如何命名变量? 在这个例子中,我将使用匈牙利应用程序,并且根本不会遇到任何潜在的问题。
谢谢!
So I am trying to switch to PEP8 notation (from a rather personal CamelCase notation) and I was wondering how you guys are tackling the cases where existing functions/variables would be overwritten?
e.g. having something like:
open, high, low, close, sum = row
would already overwrite the "open" and "sum" functions.
First, if I wouldn't use a good IDE, I wouldn't even notice that I've just overwritten important basic functions. Second, how would you name the variables instead?
In this example I would have used apps hungarian and wouldn't have encountered any potential problem at all.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
为什么不直接选择不冲突的名称呢?例如
opening_price
、close_price
和total
(如果它们代表的是这些)。虽然可以像其他回复中那样限定名称空间,但局部变量肯定不需要这样做。无论您使用哪种语言进行编程,您都有责任了解保留字;没有那么多。Why not just pick non-conflicting names? Such as
opening_price
,closing_price
andtotal
if that's what they represent. While it's possible to qualify the namespace as in the other replies, surely that shouldn't be needed for local variables. Whatever language you program in it's your job to know the reserved words; there aren't that many of them.我会使用
open_
和sum_
。I would use
open_
andsum_
.在这种特殊情况下,我将使用
namedtuple
。这会将这些名称转换为限定名称(data.open
、data.low
等)。这将消除与内置函数名称冲突的可能性,并可能提高整体可读性。
In this particular case, I'd use a
namedtuple
. This would turn those names into qualified ones (data.open
,data.low
, etc.).This would eliminate the prospect of name clashes with built-in functions, and likely improve the overall readability along the way.
如果它们都是来自同一域的值,则可以使用字典:
然后可以直接访问它们:
val['open']
。您可以迭代它们val.iteritems()
等等。If they are all values from the same domain, you can use a dictionary:
Then you can access them directly:
val['open']
. You can iterate over themval.iteritems()
and so on.Pep8 建议使用尾随下划线,但也提到在可能的情况下使用变量的同义词会更好。
Pep8 recommends using trailing underscore, however there is also mentioned that in possible cases using synonym word for the variable would be better idea.