gpt4 book ai didi

python - 在 python 中命名类和命名它们的文件之间的关联(约定?)

转载 作者:IT老高 更新时间:2023-10-28 20:28:36 27 4
gpt4 key购买 nike

在python(和其他一些语言)中,我了解到,一个类的名称应该用小写字母写,除了每个单词的第一个字母应该是大写字母。示例:

class FooBar:
...

一个类应该放在一个文件中,与该类同名。在本例中,它将是一个文件 foobar.py。如果我想在某处导入类 foo 我必须这样做:

from foobar import FooBar

这个约定让我有点困惑。我的直觉告诉我,如果文件名表示一个类,那么它的第一个字母也应该大写,比如 FooBar.py。这在文件名中看起来并不漂亮。也许有人可以告诉我这个标准约定是什么?

我希望我的问题可以理解。 :-)

最佳答案

您介绍的是标准约定。

Package and Module Names

Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.

Since module names are mapped to file names, and some file systems are case insensitive and truncate long names, it is important that module names be chosen to be fairly short -- this won't be a problem on Unix, but it may be a problem when the code is transported to older Mac or Windows versions, or DOS.

When an extension module written in C or C++ has an accompanying Python module that provides a higher level (e.g. more object oriented) interface, the C/C++ module has a leading underscore (e.g. _socket).

Class Names

Almost without exception, class names use the CapWords convention. Classes for internal use have a leading underscore in addition.

( Python Style Guide )


参见例如

from configparser import ConfigParser

(顺便说一下,在 Python 2.x 中是 ConfigParser,但在 3.x 中改为小写)。

关于python - 在 python 中命名类和命名它们的文件之间的关联(约定?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5978557/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com