Ch.3: Classes and OOP

0.0(0)
Studied by 0 people
call kaiCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/21

encourage image

There's no tags or description

Looks like no tags are added yet.

22 Terms

1
New cards
[OOP] Class
A blueprint for creating objects. It bundles data (attributes) with the functions that work on that data (methods).
2
New cards
[OOP] Object / instance
One specific thing created from a class, e.g., `rex = Dog("Rex", 3)`.
```python
class Counter:
def __init__(self):
self.count = 0

def increment(self):
self.count += 1

a = Counter()
b = Counter()
a.increment()
a.increment()
print(a.count, b.count) # → 2 0 ← each object has its own data
```
3
New cards
[OOP] Attribute vs. method
An attribute is data stored on an object (`self.name`). A method is a function defined in a class that works on the object (`rex.bark()`).
4
New cards
[OOP] self
The particular object a method was called on. Python passes it automatically as the first argument.
```python
class Greeter:
def __init__(self, name):
self.name = name

def hello(self):
return "Hi, I'm " + self.name

g = Greeter("Ann")
print(g.hello()) # → Hi, I'm Ann
print(Greeter.hello(g)) # → Hi, I'm Ann ← what g.hello() does behind the scenes
```
5
New cards
[OOP] __init__
The constructor. It runs automatically when a new object is created and sets up the object's starting attributes.
6
New cards
[OOP] Magic (dunder) methods
Methods with double underscores, like `__eq__` or `__lt__`. They let your objects work with Python's built-in tools such as `<`, `==`, `len()`, `print()`, and `sorted()`.
7
New cards
[OOP] __repr__ vs. __str__
`__repr__` is an unambiguous description for developers. `__str__` is the readable version for `print()`. If there's no `__str__`, print() uses `__repr__`.
```python
class Point:
def __init__(self, x, y):
self.x, self.y = x, y

def __repr__(self):
return f"Point({self.x}, {self.y})"

def __str__(self):
return f"({self.x}, {self.y})"

p = Point(1, 2)
print(p) # → (1, 2)
print(repr(p)) # → Point(1, 2)
print([p]) # → [Point(1, 2)] ← lists show each item's repr
```
8
New cards
[OOP] What do `__eq__` and `__lt__` let you do?
`__eq__` defines `==`. `__lt__` defines `<`, which is what `sorted()`, `min()`, and `heapq` use to compare your objects.
9
New cards
[OOP] What happens if you call sorted() on objects that have no __lt__?
It raises a TypeError, because Python doesn't know how to compare them.
```python
class Box:
def __init__(self, size):
self.size = size

try:
sorted([Box(2), Box(1)])
except TypeError:
print("TypeError") # → TypeError
```
10
New cards
[OOP] Which magic method makes `len(obj)` work?
`__len__`.
```python
class Playlist:
def __init__(self, songs):
self.songs = songs

def __len__(self):
return len(self.songs)

print(len(Playlist(["a", "b", "c"]))) # → 3
```
11
New cards
[OOP] Inheritance
One class (the child) reuses another class's (the parent's) attributes and methods: `class Cat(Animal):`.
12
New cards
[OOP] Overriding
A child class defines a method with the same name as the parent's, replacing the parent's behavior for that class.
13
New cards
[OOP] super()
Calls the parent class's version of a method, most often `super().__init__(...)` inside the child's constructor.
14
New cards
[OOP] Leading underscore, e.g., `self._size`
A convention meaning "internal, don't touch from outside the class." Python has no `private` keyword.
```python
class Account:
def __init__(self):
self._balance = 0 # internal: use the methods instead

def deposit(self, amount):
self._balance += amount

def balance(self):
return self._balance

acct = Account()
acct.deposit(50)
print(acct.balance()) # → 50
```
15
New cards
[OOP] Polymorphism
Different classes respond to the same method call in their own way, e.g., `shape.describe()` works for both a Square and a Circle.
```python
class Square:
def area(self):
return 4

class Circle:
def area(self):
return 3.14

for shape in [Square(), Circle()]:
print(shape.area()) # → 4, then 3.14
```
16
New cards
[OOP] Code: Write a Dog class with name, age, a bark() method, and a __repr__.
```python
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age

def bark(self):
return f"{self.name} says woof!"

def __repr__(self):
return f"Dog(name={self.name!r}, age={self.age})"
```
17
New cards
[OOP] Code: Write a Card class that can be sorted by rank.
```python
class Card:
def __init__(self, rank):
self.rank = rank

def __repr__(self):
return f"Card({self.rank})"

def __eq__(self, other):
return self.rank == other.rank

def __lt__(self, other):
return self.rank < other.rank
```
18
New cards
[OOP] Code: Write an Animal class with Cat (overrides speak) and Dog (inherits speak) subclasses.
```python
class Animal:
def __init__(self, name):
self.name = name

def speak(self):
return f"{self.name} makes a sound"


class Cat(Animal):
def speak(self): # overrides the parent's method
return f"{self.name} says meow"


class Dog(Animal):
pass # inherits speak() unchanged
```
19
New cards
[OOP] Code: Write a Rectangle class with area(), equal when areas match, and sortable by area.
```python
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height

def area(self):
return self.width * self.height

def __eq__(self, other):
return self.area() == other.area()

def __lt__(self, other):
return self.area() < other.area()
```
20
New cards
[OOP] Code: Write a Shape base class with describe(), and Square and Circle subclasses that override it.
```python
class Shape:
def describe(self):
return "A shape"


class Square(Shape):
def __init__(self, side):
self.side = side

def describe(self):
return f"A square with side {self.side}"


class Circle(Shape):
def __init__(self, radius):
self.radius = radius

def describe(self):
return f"A circle with radius {self.radius}"
```
21
New cards
[OOP] Code: Write a child class that extends its parent's constructor with super().
```python
class Animal:
def __init__(self, name):
self.name = name


class Puppy(Animal):
def __init__(self, name, toy):
super().__init__(name) # let Animal set self.name
self.toy = toy
```
22
New cards
[OOP] Where does OOP show up in CET 2200?
Every data structure is a class: Node, LinkedList, Stack, Queue, BST, AVLTree (often a subclass of BST), Heap, Gra