Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's convention for naming a class or method as "class" in Python?

Let's say I have a class in Python like this:

class Student:
    def __init__(self, classs):
        self.classs = classs

Now, what's convention for naming a parameter (and class property) classs? I saw classs as well as klass and I'm wondering: is there some convention for it? Didn't find it in PEP8.

like image 298
ceruleus Avatar asked Aug 02 '16 10:08

ceruleus


People also ask

What is the naming convention for classes?

Class names should be nouns, in mixed case with the first letter of each internal word capitalized. Try to keep your class names simple and descriptive. Use whole words-avoid acronyms and abbreviations (unless the abbreviation is much more widely used than the long form, such as URL or HTML).

How do you name a method in Python?

Method name in PythonUse only lowercase in method names. An underscore should separate words in a method name. Non-public method name should begin with a single underscore. Use two consecutive underscores at the beginning of a method name, if it needs to be mangled.

What is a convention in Python?

Convention means a certain way in which things are done within a community to ensure order. Similarly, Coding conventions are also a set of guidelines, but for a programming language that recommends programming style, practices, and methods.


2 Answers

PEP 8 advises to use a trailing underscore in that case: class_.

See https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles for details:

single_trailing_underscore_ : used by convention to avoid conflicts with Python keyword, e.g.

Tkinter.Toplevel(master, class_='ClassName')

like image 98
Klaus D. Avatar answered Nov 02 '22 23:11

Klaus D.


The answer of class_ from PEP 8 is awkward, in my opinion, and possibly problematic as commented elsewhere for that answer to this question. 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. 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.

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. For instance, if I were to write:

NoneType = type(None)

would you argue that it should be renamed NONE_TYPE because it's global? NoneType is a class, though it is not defined using the class keyword. Likewise Class is a class, although it's also a variable. By capitalizing it, I'm just emphasizing one aspect over another. And I do this for all variables representing types.

like image 38
David Augusto Villa Avatar answered Nov 02 '22 23:11

David Augusto Villa