A class in Python is a blueprint for creating objects, defined with the class keyword.
This page covers Class in Python. For a language-agnostic introduction, see Class.
Defining a Class#
class Player:
passpass is a placeholder that means “empty body”. By convention, class names use PascalCase: Player, OddsAndEvens, RockPaperScissors.
Adding a Constructor#
In Python, the constructor is a special
method called __init__. It runs automatically when an object is created. The first parameter is always self — a reference to the object being created.
class Player:
def __init__(self, name):
self.name = nameself.name = name stores the value on the object itself.
Adding a Method#
Every
method in a Python class takes self as its first parameter. This is how the method knows which object it belongs to.
class Player:
def __init__(self, name):
self.name = name
def greet(self):
print(f"Hello, I am {self.name}!")Creating an Object#
Call the class name as if it were a function, passing any arguments the constructor expects.
player = Player("Alice")
player.greet()Common Mistakes#
Forgetting self as the first parameter
Every method in a Python class must have self as its first parameter — including __init__. Omitting it causes a TypeError when the method is called: greet() takes 0 positional arguments but 1 was given.
Not storing data with self
Inside __init__, writing name = name creates a local variable that disappears when the method returns. Use self.name = name to attach the value to the object.
Forgetting the colon after class or def
Python uses a colon to open a block. class Player and def greet(self) both need a colon at the end. Missing it is a SyntaxError.
Using PascalCase for method names
Python convention is snake_case for methods (greet, get_name) and PascalCase for class names (Player, OddsAndEvens). Mixing these up won’t break the code but goes against the style the Python community expects.
Resources#
- Classes — Python documentation (external link) — Python.org
- Class (computer programming) (external link) — Wikipedia