iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

PartRole
__init__Runs when you call Person(...). Sets up state.
selfReference to the instance. Always the first argument.
AttributesSet via self.x = …; read via p.x.
MethodsFunctions 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):

Test yourself

Q1. The first parameter of an instance method is…
Q2. __init__ runs when…
Q3. @dataclass automates…

Discussion

Loading…