Python: 使用缩略词命名
在Python代码中,给类、方法和变量命名时,处理常见缩写的标准方式是什么?
比如说,有一个处理RSS订阅的类。你觉得应该这样命名:
class RSSClassOne:
def RSSMethod(self):
self.RSS_variable = True
class ClassRSSTwo:
def MethodRSS(self):
self.variable_RSS = True
还是这样:
class RssClassOne:
def rssMethod(self):
self.rss_variable = True
class ClassRssTwo:
def MethodRss(self):
self.variable_rss = True
也就是说,保持缩写的大小写和遵循PEP 008的建议,哪个更重要呢?
编辑:根据大家的回答,我得出的结论是,应该这样做:
class RSSClassOne:
def rss_method(self):
self.rss_variable = True
class ClassRSSTwo:
def method_rss(self):
self.variable_rss = True
3 个回答
0
我觉得,遵循PEP 8中的建议是关于编码风格的第一步。
1
我觉得第一个写法没有任何问题。因为缩写代表了一系列单词,而在Python中,class
的命名规则是每个单词的首字母都要大写,这样把缩写中的每个字母都大写也是完全可以的。
所以,第一个代码示例其实更符合Python的风格指南,可能比第二个更好。简单来说,第一个写法符合PEP8的规范,这个规范非常重要。:)
另外要记住,有时候(虽然很少)这些规则可以稍微放宽一下,这种情况也许就算是其中之一。
24
其实,PEP 8已经对这个话题有了说明,具体可以在这里找到:
注意:在使用大写字母缩写时,要把缩写的所有字母都大写。所以说,
HTTPServerError
比HttpServerError
更好。
换句话说,Python对包含缩写的命名有以下约定:
在类名中,缩写要保持大写(通常,Python中只有类名会用到这种大写风格)。
在其他地方,缩写要小写,以符合其他命名约定。
下面是一个使用ipaddress
模块的示例:
>>> 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>
>>>