Python中变量名和函数名的命名约定是什么?

2024-04-20 05:03:20 发布

您现在位置:Python中文网/ 问答频道 /正文

来自C#背景的变量和方法名的命名约定通常是camelCase或PascalCase:

// C# example
string thisIsMyVariable = "a"
public void ThisIsMyMethod()

在Python中,我看到了上面的内容,但也看到了使用下划线:

# python example
this_is_my_variable = 'a'
def this_is_my_function():

对于Python,是否有更可取、更明确的编码风格?


Tags: 方法内容stringisexamplemypublicthis
0条回答
网友
1楼 · 发布于 2024-04-20 05:03:20

David Goodger(在“代码类似于Pythonista”here)描述了PEP 8的建议如下:

  • joined_lower对于函数、方法, 属性,变量

  • 对于joined_lowerALL_CAPS 常数

  • StudlyCaps用于类

  • camelCase仅符合 已有的约定

网友
2楼 · 发布于 2024-04-20 05:03:20

Google Python Style Guide具有以下约定:

module_name, package_name, ClassName, method_name, ExceptionName, function_name, GLOBAL_CONSTANT_NAME, global_var_name, instance_var_name, function_parameter_name, local_var_name

类似的命名方案应该应用于CLASS_CONSTANT_NAME

网友
3楼 · 发布于 2024-04-20 05:03:20

请参见PythonPEP 8

Function names should be lowercase, with words separated by underscores as necessary to improve readability.

mixedCase is allowed only in contexts where that's already the prevailing style

变量。。。

Use the function naming rules: lowercase with words separated by underscores as necessary to improve readability.

就我个人而言,我之所以偏离这一点,是因为对于我自己的项目,我也更喜欢mixedCase而不是lower_case

相关问题 更多 >