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

2024-04-29 12:07:45 发布

您现在位置:Python中文网/ 问答频道 /正文

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

class FooBar:
    ...

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

from foobar import FooBar

这个会议让我有点困惑。我的直觉告诉我,如果文件名表示一个类,那么它也应该用大写字母写,比如FooBar.py。这在文件名上看起来并不好看。也许有人能告诉我,标准惯例是什么?

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


Tags: 文件py名称语言示例文件名字母大写字母
2条回答

政治公众人物8说:

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.

我还要注意的是,每个文件不一定只有一个类。相反,您应该在同一个文件中包含相关的类。(当然,在某些情况下,对文件使用一个类是可行的,但并非总是如此)

你所介绍的是标准惯例。

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

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

相关问题 更多 >