[英]What's convention for naming a class or method as "class" in Python?
Let's say I have a class in Python like this:假设我在 Python 中有一个这样的类:
class Student:
def __init__(self, classs):
self.classs = classs
Now, what's convention for naming a parameter (and class property) classs
?现在,命名参数(和类属性) classs
的约定是什么? I saw classs
as well as klass
and I'm wondering: is there some convention for it?我看到了classs
和klass
,我想知道:有什么约定吗? Didn't find it in PEP8.在 PEP8 中没有找到它。
PEP 8 advises to use a trailing underscore in that case: class_
. PEP 8 建议在这种情况下使用尾随下划线: class_
。
See https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles for details:有关详细信息,请参阅https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles :
single_trailing_underscore_ : used by convention to avoid conflicts with Python keyword, eg single_trailing_underscore_ :按惯例使用以避免与 Python 关键字冲突,例如
Tkinter.Toplevel(master, class_='ClassName')
The answer of class_
from PEP 8 is awkward, in my opinion, and possibly problematic as commented elsewhere for that answer to this question.在我看来,PEP 8 中class_
的答案很尴尬,并且可能有问题,正如其他地方对该问题的答案所评论的那样。 The PyCharm IDE seems to prefer cls
for class methods, which annoys me for its coder-happy abbreviation, while the arguably more or less readable and understandable klass
is still a misspelling. PyCharm IDE 似乎更喜欢cls
作为类方法,这让我为它的 coder-happy 缩写而烦恼,而可以说或多或少可读和可理解的klass
仍然是一个拼写错误。 So I'd like to throw out an alternative for these situations, including class wrappers and the like:所以我想为这些情况抛出一个替代方案,包括类包装器等:
I use Class
, which is not reserved due to the casing.我使用Class
,由于大小写,它没有保留。
I know a lot of people are going to say that variables names should be lowercase, but the lines between object and type, class and function, variable and pre-defined are all blurred in Python.我知道很多人会说变量名应该是小写的,但是对象和类型、类和函数、变量和预定义之间的界限在 Python 中都是模糊的。 For instance, if I were to write:例如,如果我要写:
NoneType = type(None)
would you argue that it should be renamed NONE_TYPE
because it's global?您是否会争辩说它应该重命名为NONE_TYPE
因为它是全球性的? NoneType
is a class, though it is not defined using the class
keyword. NoneType
是一个类,尽管它不是使用class
关键字定义的。 Likewise Class
is a class, although it's also a variable.同样, Class
是一个类,尽管它也是一个变量。 By capitalizing it, I'm just emphasizing one aspect over another.通过大写它,我只是强调一个方面而不是另一个方面。 And I do this for all variables representing types.我对所有代表类型的变量都这样做。
There isn't really a convention.没有真正的约定。 I've seen - and probably used - klass
, _class
, and cls
.我见过——而且可能用过—— klass
、 _class
和cls
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.