来自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是否有更可取、更明确的编码风格?


当前回答

就我个人而言,我尝试在类、mixedCase方法和函数中使用CamelCase。变量通常用下划线分隔(当我记得的时候)。这样我一眼就能知道我到底在调用什么,而不是所有东西看起来都一样。

其他回答

我个人在用其他编程语言开发时使用Java的命名约定,因为它是一致的,易于遵循。这样我就不会一直纠结于使用什么约定,而这本来不应该是我项目中最难的部分!

通常,要遵循语言标准库中使用的约定。

编码风格通常是组织内部策略/约定标准的一部分,但我认为一般来说,all_lower_case_underscore_separator风格(也称为snake_case)在python中最常见。

There is PEP 8, as other answers show, but PEP 8 is only the styleguide for the standard library, and it's only taken as gospel therein. One of the most frequent deviations of PEP 8 for other pieces of code is the variable naming, specifically for methods. There is no single predominate style, although considering the volume of code that uses mixedCase, if one were to make a strict census one would probably end up with a version of PEP 8 with mixedCase. There is little other deviation from PEP 8 that is quite as common.

无论是否在课堂上或在课堂外:

变量和函数小写,如下所示:

name = "John"
def display(name):
    print("John")

如果它们多于一个单词,则用下划线“_”分隔,如下所示:

first_name = "John"
def display_first_name(first_name):
    print(first_name)

并且,如果一个变量是一个常量,它是大写的,如下所示:

FIRST_NAME = "John"