Python 中变量和函数的命名约定是什么?

发布于 2024-07-06 16:29:12 字数 392 浏览 12 评论 0原文

来自 C# 背景的变量和方法的命名约定通常是驼峰命名法或帕斯卡命名法:

// C# example
string thisIsMyVariable = "a"
public void ThisIsMyMethod()

在 Python 中,我已经看到了上面的内容,但我也看到了使用 Snake_case:

# python example
this_is_my_variable = 'a'
def this_is_my_function():

Python 是否有更优选、更明确的编码风格?

Coming from a C# background the naming convention for variables and methods are usually either camelCase or PascalCase:

// C# example
string thisIsMyVariable = "a"
public void ThisIsMyMethod()

In Python, I have seen the above but I have also seen snake_case being used:

# python example
this_is_my_variable = 'a'
def this_is_my_function():

Is there a more preferable, definitive coding style for Python?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

谎言 2024-07-13 16:29:13

进一步了解@JohnTESlade 的回答。 Google 的 Python 风格指南 有一些非常简洁的建议,

要避免的名称

  • 单字符名称,除了
  • 任何包/模块名称中的计数器或迭代器破折号(-)
  • __double_leading_and_trailing_underscore__名称(由Python保留)

命名约定

  • “内部”是指模块内部的或者类内受保护的或私有的。
  • 前面添加一个下划线 (_) 对保护模块变量和函数有一定的支持(不包含在 import * from 中)。 在实例变量或方法前面添加双下划线 (__) 可以有效地使该变量或方法对其类私有(使用名称修饰)。
  • 将相关的类和顶级函数放在一个模块中。 与 Java 不同,无需将自己限制为每个模块一个类。
  • 使用 CapWords 作为类名称,使用 lower_with_under.py 作为模块名称。 尽管有许多名为 CapWords.py 的现有模块,但现在不鼓励这样做,因为当模块碰巧以类命名时会造成混乱。 (“等等——我写的是import StringIO还是from StringIO import StringIO?”)

源自Guido建议的指南
输入图片此处描述

further to what @JohnTESlade has answered. Google's python style guide has some pretty neat recommendations,

Names to Avoid

  • single character names except for counters or iterators
  • dashes (-) in any package/module name
  • __double_leading_and_trailing_underscore__ names (reserved by Python)

Naming Convention

  • "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?")

Guidelines derived from Guido's Recommendations
enter image description here

忘年祭陌 2024-07-13 16:29:13

正如其他答案所示,有 PEP 8,但 PEP 8 只是标准库的样式指南,并且它仅被视为其中的福音。 PEP 8 对于其他代码片段最常见的偏差之一是变量命名,特别是方法的变量命名。 尽管考虑到使用混合大小写的代码量,但不存在单一的主导风格,如果要进行严格的普查,最终可能会得到带有混合大小写的 PEP 8 版本。 与 PEP 8 相比,几乎没有其他常见的偏差。

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.

北凤男飞 2024-07-13 16:29:13

大多数Python人更喜欢下划线,但即使我使用Python已有5年多了,我仍然不喜欢它们。 它们对我来说只是看起来很丑,但也许这就是我脑子里的 Java。

我只是更喜欢 CamelCase,因为它更适合类的命名方式,使用 SomeClass.doSomething() 比使用 SomeClass.do_something() 感觉更符合逻辑。 如果你环顾一下Python的全局模块索引,你会发现两者都有,这是因为它是来自各种来源的库的集合,随着时间的推移而增长,而不是由像Sun这样的公司开发的具有严格编码规则的东西。 我想说的底线是:使用你更喜欢的任何东西,这只是个人品味的问题。

Most python people prefer underscores, but even I am using python since more than 5 years right now, I still do not like them. They just look ugly to me, but maybe that's all the Java in my head.

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.

暮色兮凉城 2024-07-13 16:29:13

就我个人而言,我尝试对类、混合大小写方法和函数使用驼峰命名法。 变量通常用下划线分隔(当我记得时)。 这样我就能一眼看出我到底在调用什么,而不是所有东西看起来都一样。

Personally I try to use CamelCase for classes, mixedCase methods and functions. Variables are usually underscore separated (when I can remember). This way I can tell at a glance what exactly I'm calling, rather than everything looking the same.

雪花飘飘的天空 2024-07-13 16:29:13

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

TL;DR 它说snake_case比camelCase更具可读性。 这就是为什么现代语言尽可能使用(或应该使用)蛇。

There is a paper about this: http://www.cs.kent.edu/~jmaletic/papers/ICPC2010-CamelCaseUnderScoreClouds.pdf

TL;DR It says that snake_case is more readable than camelCase. That's why modern languages use (or should use) snake wherever they can.

萌吟 2024-07-13 16:29:13

无论是在课堂上还是课堂外

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

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

如果它们不止一个单词中,它们之间用下划线“_”分隔,如下所示:

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

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

FIRST_NAME = "John"

Whether or not being in class or out of class:

A variable and function are lowercase as shown below:

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

And if they're more than one word, they're separated with underscore "_" as shown below:

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

And, if a variable is a constant, it's uppercase as shown below:

FIRST_NAME = "John"
御弟哥哥 2024-07-13 16:29:13

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

The coding style is usually part of an organization's internal policy/convention standards, but I think in general, the all_lower_case_underscore_separator style (also called snake_case) is most common in python.

梦一生花开无言 2024-07-13 16:29:13

Lenin 告诉过……我也来自 Java/C# 世界。 还有 SQL。
仔细审视自己,试图找到第一眼可以理解的复杂结构的例子,比如列表字典中的列表,其中一切都是对象。
对我来说 - 驼峰命名法或其变体应该成为任何语言的标准。 对于复杂的句子应保留下划线。

Lenin has told... I'm from Java/C# world too. And SQL as well.
Scrutinized myself in attempts to find first sight understandable examples of complex constructions like list in the dictionary of lists where everything is an object.
As for me - camelCase or their variants should become standard for any language. Underscores should be preserved for complex sentences.

谁许谁一生繁华 2024-07-13 16:29:13

我个人在使用其他编程语言进行开发时使用 Java 的命名约定,因为它是一致且易于遵循的。 这样我就不会一直为使用哪些约定而苦苦挣扎,而这不应该是我的项目中最困难的部分!

I personally use Java's naming conventions when developing in other programming languages as it is consistent and easy to follow. That way I am not continuously struggling over what conventions to use which shouldn't be the hardest part of my project!

安人多梦 2024-07-13 16:29:13

PEP 8 是指南,而不是法律。 它是 Python 之上的一个选项,而不是官方语言的一部分。 如果每个人都使用相同的风格,那么在大公司中这将是首选。

我家里所有的Python程序都可以完美地使用camelCaseNames,我不会改变这一点,除非人们可以证明我的代码运行速度较慢或有错误的行为。 然而,在我的工作中,他们希望设计师遵循相同的规则,因此选择了带有一组附加规则的 PEP 8。 这并不意味着他们使用 autopep8,有很多工具可以兼容 PEP8,但有一些小的变化,例如 black、flake8、autopep8。

改进代码以使其符合 PEP8 的工具主要基于意见管理。 因此,如果人们使用“必须有”、“应该有”、“应有”等词语,则应将其替换为“可能有”。 我会询问贵公司他们的偏好。

除了 PEP8,我还可以推荐 pylint 和 mypy,这些工具确实可以在代码中找到问题和阻碍。

PEP 8 is a guideline, not a law. It is an option on top of Python, not part of the official language. If everybody uses the same style, this would be preferred in a bigger company.

All my Python programs at home run perfect with camelCaseNames, I will not change this unless people can prove my code is runner slower or has wrong behavior. However, on my job they want designers to follow the same rules and therefore have chosen for PEP 8 with a set of additional rules. This does not mean they use autopep8, there are many tools to be PEP8 compliant with small variations like black, flake8, autopep8.

The tools that improve code to be PEP8 compliant are mainly based on opinion management. So, if people use words like "Must have", "Should have", "Shall have", these should be replaced by "could have". I would ask your company their preference.

Next to PEP8, I could recommend pylint and mypy, those tools really find issues and showstoppers in your code.

七月上 2024-07-13 16:29:13

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

Typically, one follow the conventions used in the language's standard library.

女中豪杰 2024-07-13 16:29:12

请参阅 Python PEP 8:函数和变量名称

函数名称应小写,单词之间用下划线分隔,以提高可读性。< /p>

变量名称遵循与函数名称相同的约定。

mixedCase 仅在已成为流行风格的上下文中才允许使用(例如 threading.py),以保留向后兼容性。

See Python PEP 8: Function and Variable Names:

Function names should be lowercase, with words separated by underscores as necessary to improve readability.

Variable names follow the same convention as function names.

mixedCase is allowed only in contexts where that's already the prevailing style (e.g. threading.py), to retain backwards compatibility.

几度春秋 2024-07-13 16:29:12

Google Python 样式指南具有以下约定:

模块名称包名称类名方法名称异常名称function_nameGLOBAL_CONSTANT_NAMEglobal_var_nameinstance_var_namefunction_parameter_namelocal_var_name >.

类似的命名方案应该应用于CLASS_CONSTANT_NAME

The Google Python Style Guide has the following convention:

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.

A similar naming scheme should be applied to a CLASS_CONSTANT_NAME

朦胧时间 2024-07-13 16:29:12

David Goodger(在“像 Pythonista 一样编程”此处) PEP 8 建议如下所述:

  • joined_lower 用于函数、方法、
    属性、变量

  • joined_lowerALL_CAPS
    常量

  • StudlyCaps 用于类

  • camelCase 仅符合
    预先存在的约定

David Goodger (in "Code Like a Pythonista" here) describes the PEP 8 recommendations as follows:

  • joined_lower for functions, methods,
    attributes, variables

  • joined_lower or ALL_CAPS for
    constants

  • StudlyCaps for classes

  • camelCase only to conform to
    pre-existing conventions

我的奇迹 2024-07-13 16:29:12

正如 Python 代码风格指南 承认的那样,

Python 的命名约定
图书馆有点乱,所以我们
永远不会完全一致

请注意,这仅指 Python 的标准库。 如果他们不能保持一致,那么几乎没有希望为所有 Python 代码建立一个普遍遵守的约定,不是吗?

由此以及这里的讨论,我会推断,如果在转换到 Python 时继续使用 Java 或 C#(清晰且完善的)变量和函数命名约定,那么这不是是一种可怕的罪过。 当然,请记住,最好遵守代码库/项目/团队的流行风格。 正如《Python 风格指南》所指出的,内部一致性最为重要。

请随意将我视为异教徒。 :-) 和 OP 一样,我也不是“Pythonista”,至少现在还不是。

As the Style Guide for Python Code admits,

The naming conventions of Python's
library are a bit of a mess, so we'll
never get this completely consistent

Note that this refers just to Python's standard library. If they can't get that consistent, then there hardly is much hope of having a generally-adhered-to convention for all Python code, is there?

From that, and the discussion here, I would deduce that it's not a horrible sin if one keeps using e.g. Java's or C#'s (clear and well-established) naming conventions for variables and functions when crossing over to Python. Keeping in mind, of course, that it is best to abide with whatever the prevailing style for a codebase / project / team happens to be. As the Python Style Guide points out, internal consistency matters most.

Feel free to dismiss me as a heretic. :-) Like the OP, I'm not a "Pythonista", not yet anyway.

水染的天色ゝ 2024-07-13 16:29:12

如前所述,PEP 8 规定对变量、方法和函数使用 lower_case_with_underscores

我更喜欢对变量使用 lower_case_with_underscores ,对方法和函数使用 mixedCase ,这样可以使代码更加明确和可读。 因此遵循Python 之禅“显式优于隐式”和“可读性”计数”

As mentioned, PEP 8 says to use lower_case_with_underscores for variables, methods and functions.

I prefer using lower_case_with_underscores for variables and mixedCase for methods and functions makes the code more explicit and readable. Thus following the Zen of Python's "explicit is better than implicit" and "Readability counts"

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文