在 python 中对与关键字名称相同的变量使用下划线
using underscore for a variable as same as keyword name in python
当你想使用一些与Python中的关键字同名的变量时,我应该使用_keyword
还是keyword_
?
我知道我们应该使用下划线以免弄乱它,但我不确定下划线的位置。下划线的位置重要吗?
例如,我不确定是哪一个(True_
或 _True
)?
或者在其他情况下,当你想在你的项目中使用一个内置函数的名称作为你的变量之一时,你应该怎么做?例如,我处理股票数据,我的股票变量中有一个开放变量。那我应该写open_
还是_open
?
如果您想在 class 中使用这些类型的 variables/methods 怎么办?现在在什么地方使用下划线重要吗?
如https://pep8.org/#function-and-method-arguments
所述
If a function argument’s name clashes with a reserved keyword, it is generally better to append a single trailing underscore rather than use an abbreviation or spelling corruption. Thus class_
is better than clss. (Perhaps better is to avoid such clashes by using a synonym.)
请注意前缀下划线,例如_class
通常意味着私有 class 属性或方法,例如:
class MyClass:
def __init__(self):
self._my_private_variable = 1
def _my_private_method(self):
pass
https://pep8.org/#descriptive-naming-styles
中的更多信息
_single_leading_underscore
: weak “internal use” indicator. E.g. from M import *
does not import objects whose name starts with an underscore.
single_trailing_underscore_
: used by convention to avoid conflicts
with Python keyword
当你想使用一些与Python中的关键字同名的变量时,我应该使用_keyword
还是keyword_
?
我知道我们应该使用下划线以免弄乱它,但我不确定下划线的位置。下划线的位置重要吗?
例如,我不确定是哪一个(True_
或 _True
)?
或者在其他情况下,当你想在你的项目中使用一个内置函数的名称作为你的变量之一时,你应该怎么做?例如,我处理股票数据,我的股票变量中有一个开放变量。那我应该写open_
还是_open
?
如果您想在 class 中使用这些类型的 variables/methods 怎么办?现在在什么地方使用下划线重要吗?
如https://pep8.org/#function-and-method-arguments
所述If a function argument’s name clashes with a reserved keyword, it is generally better to append a single trailing underscore rather than use an abbreviation or spelling corruption. Thus
class_
is better than clss. (Perhaps better is to avoid such clashes by using a synonym.)
请注意前缀下划线,例如_class
通常意味着私有 class 属性或方法,例如:
class MyClass:
def __init__(self):
self._my_private_variable = 1
def _my_private_method(self):
pass
https://pep8.org/#descriptive-naming-styles
中的更多信息
_single_leading_underscore
: weak “internal use” indicator. E.g.from M import *
does not import objects whose name starts with an underscore.
single_trailing_underscore_
: used by convention to avoid conflicts with Python keyword