Python:使用首字母缩略词命名

2024-10-01 11:20:15 发布

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

在Python代码中,当命名类、方法和变量时,处理众所周知的首字母缩略词的规范方法是什么?在

例如,考虑一个处理RSS提要的类。宁愿这样:

class RSSClassOne:
    def RSSMethod(self):
        self.RSS_variable = True

class ClassRSSTwo:
    def MethodRSS(self):
        self.variable_RSS = True

或者这个:

^{pr2}$

也就是说,保持首字母缩略词大写还是保留PEP 008的建议更重要?在

编辑:从答案中,我得出结论,这将是一条出路:

class RSSClassOne:
    def rss_method(self):
        self.rss_variable = True

class ClassRSSTwo:
    def method_rss(self):
        self.variable_rss = True

Tags: 方法代码selftruedefvariable命名method
3条回答

嗯,事实证明PEP8已经讨论了这个主题here

Note: When using abbreviations in CapWords, capitalize all the letters of the abbreviation. Thus HTTPServerError is better than HttpServerError.

换句话说,Python对包含首字母缩略词的名称的约定是:

  1. 在类名中保持首字母大写(通常是Python中唯一使用CapWords的部分)。

  2. 在其他地方,使它们小写以符合另一个naming conventions

下面是使用^{} module的演示:

>>> import ipaddress  # IP is lowercase because this is a module
>>> ipaddress.IPv4Address  # IP is uppercase because this is a class
<class 'ipaddress.IPv4Address'>
>>> ipaddress.ip_network  # IP is lowercase because this is a function
<function ip_network at 0x0242C468>
>>>

我不认为第一个有什么问题。由于首字母缩略词代表一系列单词,在Python class中,在每个单词的开头CamelCase中,将首字母(单词)大写是完全可以的。在

因此,第一个代码示例可能比第二个更符合Python代码的样式指南。简而言之,第一个因为PEP8构象非常重要。:)

同时请记住,有时有时(尽管很少)这些规则可能会稍微弯曲。这可以被认为是其中之一。在

我想说,遵循pep8中的建议是与编码风格相关的第一件事。在

相关问题 更多 >