Lesson 02
Classes — Programmer-Defined Types in Python
Learn what a Python class is: a programmer-defined type of data members and methods, with no instance memory until you create an object.
A class is a type you invent. It collects the fields and the functions that belong together. Those functions are called methods.
Use the playground at the bottom of this page, then take the quiz.
What you will learn
- Why classes exist
- The
classkeyword - The definition: data members plus methods
- Why the class itself does not allocate instance memory
The picture
Built-in types such as int and str already exist. A class lets you store a custom combination, such as a label and a seat count, and put the operations for that combination in the same place.
class Badge:
...class is the keyword. Badge is the new type name. Class names are the programmer-defined data types of the program.
Two facts keep this from getting fuzzy:
| Moment | What exists |
|---|---|
| You define the class | The blueprint is loaded once. Instance fields do not have memory yet. |
| You create an object | That object gets the fields and can call the methods. |
One class definition is enough. You will make many objects from it in the objects lesson. Every object-oriented program in this module starts with a class. Without the class, there is no type to instantiate, and Python raises NameError.
Example
class Badge:
pass
first = Badge()
first.label = "Avery Lane"
print(first.label)
print(type(first).__name__)pass is a valid empty class body. The name Badge exists before first does. The label is stored on the object, not on the class statement itself. The playground prints both the label and the type name.
Key takeaways
-
A class is a collection of data members and methods
-
classintroduces a programmer-defined type -
Defining the class does not allocate instance memory
-
Object creation is what creates that memory
-
Next: Inside a Class — data, methods,
self, andcls -
Previous: OOP Roadmap
Loading playground…
Check your understanding
Classes quiz
The purpose of a class is to:
1 / 10