Python Classes & Objects
A class is a blueprint for objects — data fields plus the methods that act on them. Define with class; create instances by calling the class.
The basics
PYTHON
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f'Hi, I am {self.name}'
p = Person('Ada', 36)
print(p.name) # Ada
print(p.greet()) # Hi, I am Ada
Anatomy
| Part | Role |
|---|---|
__init__ | Runs when you call Person(...). Sets up state. |
self | Reference to the instance. Always the first argument. |
| Attributes | Set via self.x = …; read via p.x. |
| Methods | Functions defined inside the class. |
Dunder methods
"Dunder" = double underscore. They wire your class into Python's protocols:
PYTHON
class Money:
def __init__(self, amount):
self.amount = amount
def __repr__(self):
return f'Money({self.amount})'
def __add__(self, other):
return Money(self.amount + other.amount)
print(Money(100) + Money(50)) # Money(150)
dataclasses — less boilerplate
PYTHON
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
p = Person('Ada', 36)
print(p) # Person(name='Ada', age=36)
Tip: Reach for
dataclass for "objects that mostly hold data". Use a plain class when behaviour is the point.Example
Example
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f'Hi, I am {self.name}'
p = Person('Ada', 36)
print(p.greet())
Try it Yourself »
Exercise
The constructor method is named…
def
(self, name):
Double-underscore init double-underscore.
Discussion
Loading…