如何建议在Python中使用自定义双下划线变量? [英] How recommended is using custom double underscore variables in Python?
问题描述
我想知道,是否建议/Pythonic在Python脚本中定义和使用自定义双下划线变量/函数?例如,在SQLAlchemy或__validateitem__()
中使用的__tablename__
(自定义函数,在将__setitem__()
应用于项目之前先对其进行验证).
I was wondering, is it recommended/Pythonic to define and use custom double underscore variables/functions in a Python script? For example, __tablename__
as used in SQLAlchemy or __validateitem__()
(a custom function that validates an item before applying __setitem__()
to it).
如果它确实定义了某种神奇的事情发生了,或者确实以某种特殊方式使用了特定的变量/函数(例如上述两个示例),那么我觉得使用它们是个好主意.
If it does define that something magic happens, or that that specific variable/function is used indeed in a special way (like the two above examples), I feel it is a good idea using them.
我对有关最佳编码实践和使用这种命名方式的潜在风险的争论很感兴趣.
I am interested in arguments on both best coding practices and potential risks in using this kind of naming.
推荐答案
来自PEP8:
__double_leading_and_trailing_underscore__
:存在于用户控制的名称空间中的魔术"对象或属性.例如.__init__
,__import__
或__file__
.千万不要发明这样的名字;只能按记录使用它们.
__double_leading_and_trailing_underscore__
: "magic" objects or attributes that live in user-controlled namespaces. E.g.__init__
,__import__
or__file__
. Never invent such names; only use them as documented.
因此,建议不要对自己的变量使用双下划线语法.
So, the advice is not to use the double underscore syntax for your own variables.
这篇关于如何建议在Python中使用自定义双下划线变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!