来自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代码风格指南所承认的那样,
Python的命名约定 图书馆有点乱,所以我们 永远不能完全一致
注意,这只是指Python的标准库。如果他们不能保持一致,那么几乎没有希望为所有Python代码拥有一个普遍遵守的约定,不是吗?
从这一点,以及这里的讨论,我可以推断,如果一个人在过渡到Python时继续使用例如Java或c#的(清晰而完善的)变量和函数命名约定,这并不是一个可怕的罪恶。当然,要记住,最好是遵循代码库/项目/团队的流行风格。正如Python风格指南所指出的,内部一致性是最重要的。
尽管把我当异教徒看待吧。:-)和OP一样,我不是一个“Pythonista”,至少现在还不是。
其他回答
@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?")
指南源自圭多的建议
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.
就我个人而言,我尝试在类、mixedCase方法和函数中使用CamelCase。变量通常用下划线分隔(当我记得的时候)。这样我一眼就能知道我到底在调用什么,而不是所有东西看起来都一样。
有一篇关于这方面的论文:http://www.cs.kent.edu/~jmaletic/papers/ICPC2010-CamelCaseUnderScoreClouds.pdf
它说snake_case比camelCase可读性更好。这就是为什么现代语言在任何可能的地方都使用(或应该使用)蛇。
如前所述,PEP 8要求对变量、方法和函数使用lower_case_with_下划线。
我更喜欢使用lower_case_with_下划线的变量和mixedCase的方法和函数,使代码更显式和可读。因此,遵循Python的“显式优于隐式”和“可读性很重要”的禅意。