[concept]OOP & Tooling
Classes & Objects
# theory
A class is a blueprint. An object is one thing built from it. __init__ runs
when you create the object and sets up its data; self is the object itself.
class Counter:
def __init__(self):
self.count = 0
def increment(self):
self.count += 1
Methods are functions that live on the class and take self first. You call
them on an instance: c = Counter(); c.increment().
__str__ controls what print(obj) shows. Without it you get the ugly
default <__main__.Counter object at 0x...>.
class Rectangle:
def __init__(self, w, h):
self.w = w
self.h = h
def area(self):
return self.w * self.h
def __str__(self):
return f"Rectangle {self.w}x{self.h}"
The mental model: data lives on self, behavior lives in methods, and each
object carries its own copy of the data.
# examples [2]
# example 01 · a class with state and behavior
__init__ sets up data, methods change or read it
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
🐍
# example 02 · __str__ makes print() readable
Define __str__ so the object prints as something useful
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
🐍
# challenges [2]
# challenge 01/02todo
Define a class Counter with __init__ setting self.count = 0, an increment() method that adds 1, and a value() method that returns the count. Create one, increment it twice, and print it as count=<value>.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
🐍
# challenge 02/02todo
Define a class Rectangle with __init__(self, w, h), an area() method, and a __str__ that returns 'Rectangle WxH'. Build Rectangle(3, 4), print the object, then print its area.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
🐍