Python Reference ยท Statements and Keywords
The class statement
Reference for the Python class statement: attributes, methods, inheritance, class versus instance variables, keyword arguments and the usual mistakes.
The class statement defines a new type. Its body runs once, immediately, in its own namespace; whatever names it creates (methods, constants, other attributes) become the attributes of the class object. Calling the class then creates instances.
Classes bundle data and behavior. Methods are ordinary functions whose first parameter, conventionally self, receives the instance. Parent classes in parentheses provide inheritance.
class Point: def __init__(self, x, y): self.x = x self.y = y
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
class Name: body class Name(Base1, Base2, keyword=value): body
| Part | Description |
|---|---|
Name |
The identifier that is bound to the new class. |
Base1, Base2 |
Optional base classes. With none given, the class inherits from object. |
keyword=value |
Optional keyword arguments passed to the metaclass, most often metaclass=..., or to __init_subclass__(). |
body |
Statements run in a fresh namespace; it must contain at least one statement (use pass or a docstring). |
Result: a class object bound to Name. Decorators placed above class are applied to it after creation.
Usage notes
selfis explicit. Instance methods receive the instance as their first argument. Forgetting it in the definition givesTypeError: takes 0 positional arguments but 1 was given.- Class vs instance attributes. Reading
obj.namelooks at the instance first, then the class and its bases. Assigning throughobj.name = ...always creates or updates an instance attribute and never changes the class attribute. - Shared mutable defaults. A list or dict defined in the class body is shared by every instance. Create per-instance containers in
__init__(). - The body is not a function scope. Methods cannot see names from the class body directly; use
self.nameorClassName.name. - Names with two leading underscores (and no trailing ones) are name-mangled to
_ClassName__name, which avoids accidental clashes in subclasses. It is not true privacy. - Special methods such as
__init__,__repr__and__eq__plug your class into language features. Defining__eq__without__hash__makes instances unhashable. - Everything is dynamic. Classes can be modified after creation and new ones built with the three-argument
type(name, bases, namespace). - Prefer composition when a class only needs to use another, not be a specialization of it. For plain data holders consider
dataclasses. - Python 3.12+ also allows type parameters:
class Box[T]: ....
Related
def,type(),super(),isinstance()- Inheritance and MRO, Dataclasses overview
- Lessons: Classes, Inheritance, Methods