L4Β·OOP & Errors

πŸ›οΈClasses & Instances

Blueprints for objects with state and behavior.

classself__init__instance

Β§ 1Anatomy

class Name: body. __init__ initializes each new instance. self is the instance passed automatically.

Β§ 2Attributes

Instance attributes live on self. Class attributes are shared across instances.

Β§ 3Methods

Regular methods take self. @classmethod takes cls. @staticmethod takes neither.

Animated step-through

step 1 / 6// Dog('Fido', 3) β€” allocate + call __init__
1class Dog:​
2 species = "Canis familiaris" # class attr​
3 def __init__(self, name, age):​
4 self.name = name​
5 self.age = age​
6 def bark(self):​
7 return f"{self.name} says woof"​
8​
9fido = Dog("Fido", 3)​
10print(fido.bark())​
11print(fido.species)​
Variables
β€” none yet β€”
Call stack
<module>

Try it live Β· Python runs in your browser

Loading playground…

Checkpoint quiz

Question 1 / 2
What does __init__ do?