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


当前回答

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

其他回答

有一篇关于这方面的论文:http://www.cs.kent.edu/~jmaletic/papers/ICPC2010-CamelCaseUnderScoreClouds.pdf

它说snake_case比camelCase可读性更好。这就是为什么现代语言在任何可能的地方都使用(或应该使用)蛇。

参见Python PEP 8:函数和变量名:

函数名应该是小写的,单词之间用下划线分隔,以提高可读性。 变量名遵循与函数名相同的约定。 mixedCase只允许在已经是流行风格的上下文中使用(例如threading.py),以保持向后兼容性。

大多数使用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.

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

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