来自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是否有更可取、更明确的编码风格?
来自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是否有更可取、更明确的编码风格?
当前回答
无论是否在课堂上或在课堂外:
变量和函数小写,如下所示:
name = "John"
def display(name):
print("John")
如果它们多于一个单词,则用下划线“_”分隔,如下所示:
first_name = "John"
def display_first_name(first_name):
print(first_name)
并且,如果一个变量是一个常量,它是大写的,如下所示:
FIRST_NAME = "John"
其他回答
谷歌Python风格指南有以下约定:
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应该应用类似的命名方案
参见Python PEP 8:函数和变量名:
函数名应该是小写的,单词之间用下划线分隔,以提高可读性。 变量名遵循与函数名相同的约定。 mixedCase只允许在已经是流行风格的上下文中使用(例如threading.py),以保持向后兼容性。
编码风格通常是组织内部策略/约定标准的一部分,但我认为一般来说,all_lower_case_underscore_separator风格(也称为snake_case)在python中最常见。
@JohnTESlade的回答更进一步。谷歌的python风格指南有一些非常简洁的建议,
避免使用的名字
除计数器或迭代器外的单字符名称 在任何包/模块名称中使用破折号(-) \ __double_leading_and_trailing_下划线名称(由Python保留)
命名约定
"Internal" means internal to a module or protected or private within a class. Prepending a single underscore (_) has some support for protecting module variables and functions (not included with import * from). Prepending a double underscore (__) to an instance variable or method effectively serves to make the variable or method private to its class (using name mangling). Place related classes and top-level functions together in a module. Unlike Java, there is no need to limit yourself to one class per module. Use CapWords for class names, but lower_with_under.py for module names. Although there are many existing modules named CapWords.py, this is now discouraged because it's confusing when the module happens to be named after a class. ("wait -- did I write import StringIO or from StringIO import StringIO?")
指南源自圭多的建议
无论是否在课堂上或在课堂外:
变量和函数小写,如下所示:
name = "John"
def display(name):
print("John")
如果它们多于一个单词,则用下划线“_”分隔,如下所示:
first_name = "John"
def display_first_name(first_name):
print(first_name)
并且,如果一个变量是一个常量,它是大写的,如下所示:
FIRST_NAME = "John"