来自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是否有更可取、更明确的编码风格?
当前回答
谷歌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应该应用类似的命名方案
其他回答
如前所述,PEP 8要求对变量、方法和函数使用lower_case_with_下划线。
我更喜欢使用lower_case_with_下划线的变量和mixedCase的方法和函数,使代码更显式和可读。因此,遵循Python的“显式优于隐式”和“可读性很重要”的禅意。
大多数使用python的人更喜欢下划线,但即使我已经使用python 5年多了,我仍然不喜欢它们。我只是觉得它们很丑,但也许这就是我脑子里的爪哇。
I simply like CamelCase better since it fits better with the way classes are named, It feels more logical to have SomeClass.doSomething() than SomeClass.do_something(). If you look around in the global module index in python, you will find both, which is due to the fact that it's a collection of libraries from various sources that grew overtime and not something that was developed by one company like Sun with strict coding rules. I would say the bottom line is: Use whatever you like better, it's just a question of personal taste.
有一篇关于这方面的论文:http://www.cs.kent.edu/~jmaletic/papers/ICPC2010-CamelCaseUnderScoreClouds.pdf
它说snake_case比camelCase可读性更好。这就是为什么现代语言在任何可能的地方都使用(或应该使用)蛇。
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.
David Goodger(在这里的“像Pythonista一样编码”中)描述了PEP 8的建议如下:
Joined_lower函数,方法, 属性、变量 joined_lower或ALL_CAPS for 常量 课程用的studlycap 骆驼案只符合 已有的约定