Creating Python Classes
Learn about creating Python classes and adding attributes, methods, and additional arguments.
We'll cover the following
Introduction
We don’t have to write much Python code to realize that Python is a very clean language. When we want to do something, we can just do it, without having to set up a bunch of prerequisite codes. The ubiquitous hello world in Python, as we’ve likely seen, is only one line. Similarly, the simplest class in Python 3 looks like this:
class MyFirstClass:
pass
There’s our first object-oriented program! The class definition starts with
the class
keyword. This is followed by a name (of our choice) identifying the class and is terminated with a colon :
.
Note: The class name must follow standard Python variable naming rules (it must start with a letter or underscore, and can only be comprised of letters, underscores, or numbers). In addition, the Python style guide (search the web for PEP 8) recommends that classes should be named using what PEP 8 calls CapWords notation (start with a capital letter; any subsequent words should also start with a capital).
The class definition line is followed by the class contents, indented. As with other Python constructs, indentation is used to delimit the classes, rather than braces, keywords, or brackets, as many other languages use. Also, in line with the style guide, use four spaces for indentation unless we have a compelling reason not to (such as fitting in with somebody else’s code that uses tabs for indents).
Since our first class doesn’t actually add any data or behaviors, we simply use the pass keyword on the second line as a placeholder to indicate that no further action needs to be taken.
We might think there isn’t much we can do with this most basic class, but it does allow us to instantiate objects of that class. The following interpreter session demonstrates a basic interaction with this class:
Get hands-on with 1400+ tech skills courses.