# How Object-Oriented Programming Is Taught in Python-100-Days: A Complete Guide to Days 31-35

> Discover how Python-100-Days teaches object-oriented programming from encapsulation to metaclasses over five days. Explore practical code examples and master OOP concepts.

- Repository: [骆昊/Python-100-Days](https://github.com/jackfrued/Python-100-Days)
- Tags: tutorial
- Published: 2026-02-24

---

**The Python-100-Days repository teaches object-oriented programming through a progressive five-day curriculum (Days 31-35) that moves from basic encapsulation and inheritance to advanced topics like metaclasses and the iterator protocol, with each concept demonstrated in isolated, runnable scripts located in `Day31-35/code/`.**

The `jackfrued/Python-100-Days` repository is one of the most popular Chinese-language Python learning resources on GitHub. Its object-oriented programming section spans Days 31 through 35 and employs a bite-sized, example-driven approach. Rather than overwhelming learners with theory, each script in `Day31-35/code/` isolates a single OOP concept—from basic class definitions to metaclasses—providing a self-contained `main()` function that demonstrates the concept in action.

## The Progressive Curriculum Structure

The OOP module follows a **spiral learning** pattern. Days 31-35 are organized to build upon each previous lesson, starting with the three pillars of OOP and advancing to Python-specific object model features. Each file in `Day31-35/code/` focuses on exactly one concept, making it easy to experiment with modifications without breaking unrelated functionality.

The teaching flow covers:

- **Encapsulation** via properties and data hiding
- **Inheritance** and **polymorphism** through employee hierarchies
- **Abstract base classes** and the **Factory pattern**
- **Iterators** and the iterator protocol
- **Magic methods** for collection integration
- **Multiple inheritance** and **Method Resolution Order (MRO)**
- **Metaclasses** and the **Singleton pattern**

## Core OOP Pillars in Python

### Encapsulation with Properties

The repository introduces **encapsulation** in [`Day31-35/code/example04.py`](https://github.com/jackfrued/Python-100-Days/blob/main/Day31-35/code/example04.py) through a `Thing` class that bundles data and behavior. The class stores `name`, `price`, and `weight` as attributes while exposing a computed `value` property to maintain read-only access to the price-to-weight ratio.

```python
class Thing(object):
    """Simple item with weight‑price ratio."""
    def __init__(self, name, price, weight):
        self.name = name
        self.price = price
        self.weight = weight

    @property
    def value(self):
        """Return price‑to‑weight ratio."""
        return self.price / self.weight

```

### Inheritance and Abstract Base Classes

[`Day31-35/code/example12.py`](https://github.com/jackfrued/Python-100-Days/blob/main/Day31-35/code/example12.py) demonstrates **inheritance** through an employee management system. The `Employee` class is declared with `metaclass=ABCMeta` and defines an abstract method `get_salary()`, forcing concrete subclasses to implement their own salary calculation logic.

```python
from abc import ABCMeta, abstractmethod

class Employee(metaclass=ABCMeta):
    @abstractmethod
    def get_salary(self):
        pass

class Manager(Employee):
    def get_salary(self):
        return 15000.0

```

### Polymorphism in Employee Hierarchies

The same [`example12.py`](https://github.com/jackfrued/Python-100-Days/blob/main/example12.py) file illustrates **polymorphism** through the `Programmer`, `Manager`, and `Salesman` subclasses. Each implements `get_salary()` differently, allowing the caller to treat any `Employee` instance uniformly without knowing its concrete type.

## Advanced Python OOP Features

### Custom Iterators

[`Day31-35/code/example15.py`](https://github.com/jackfrued/Python-100-Days/blob/main/Day31-35/code/example15.py) teaches the **iterator protocol** by implementing `PrimeIter` and `FibIter` classes. These implement `__iter__` and `__next__` methods, allowing them to be used directly in `for` loops.

```python
class PrimeIter:
    def __init__(self, lo, hi):
        self.current = lo - 1
        self.hi = hi

    def __iter__(self):
        return self

    def __next__(self):
        self.current += 1
        while self.current <= self.hi:
            for i in range(2, int(self.current**0.5) + 1):
                if self.current % i == 0:
                    break
            else:
                return self.current
            self.current += 1
        raise StopIteration()

```

### Magic Methods for Collection Compatibility

[`Day31-35/code/example16.py`](https://github.com/jackfrued/Python-100-Days/blob/main/Day31-35/code/example16.py) demonstrates how to integrate custom classes with Python's built-in collections. The `Student` class overrides `__hash__`, `__eq__`, `__str__`, and `__repr__`, while the `School` class implements `__setitem__` and `__getitem__` to behave like a dictionary.

```python
class Student:
    __slots__ = ('stuid', 'name')
    def __init__(self, stuid, name):
        self.stuid = stuid
        self.name = name

    def __hash__(self):
        return hash((self.stuid, self.name))

    def __eq__(self, other):
        return (self.stuid, self.name) == (other.stuid, other.name)

    def __repr__(self):
        return f'Student({self.stuid}, {self.name})'

```

### Multiple Inheritance and Method Resolution Order

[`Day31-35/code/example17.py`](https://github.com/jackfrued/Python-100-Days/blob/main/Day31-35/code/example17.py) explores Python's **multiple inheritance** and **Method Resolution Order (MRO)**. The file uses classes `A`, `B`, `C`, and `D` to demonstrate how Python resolves method calls in complex inheritance hierarchies.

```python
class A: 
    def greet(self): print('A')

class B(A): pass
class C(A):
    def greet(self): print('C')

class D(B, C): pass

print(D.mro())   # [<class '__main__.D'>, <class '__main__.B'>,

                  #  <class '__main__.C'>, <class '__main__.A'>, <class 'object'>]

D().greet()      # prints 'C' because C appears before A in the MRO

```

The file also demonstrates **mix-ins** through `SetOnceMappingMixin` and `SetOnceDict`, showing how to add custom behavior to built-in types while preserving the MRO.

### Metaclasses and the Singleton Pattern

[`Day31-35/code/example18.py`](https://github.com/jackfrued/Python-100-Days/blob/main/Day31-35/code/example18.py) introduces **metaclasses** by implementing `SingletonMeta`. This metaclass enforces that only one instance of a class can exist, demonstrating Python's powerful metaclass machinery for controlling class creation.

## Practical Applications and Design Patterns

### The Factory Pattern

The `EmployeeFactory.create()` method in [`Day31-35/code/example12.py`](https://github.com/jackfrued/Python-100-Days/blob/main/Day31-35/code/example12.py) demonstrates the **Factory Method** pattern. This static method decouples object creation from usage by mapping string codes to concrete classes.

```python
class EmployeeFactory:
    @staticmethod
    def create(emp_type, *args, **kwargs):
        mapping = {'M': Manager, 'P': Programmer, 'S': Salesman}
        return mapping[emp_type.upper()](*args, **kwargs)

```

### Domain Modeling with Enums

[`Day31-35/code/example14.py`](https://github.com/jackfrued/Python-100-Days/blob/main/Day31-35/code/example14.py) models a poker game using **enumerations** and composition. The `Suite` enum represents card suits, while the `Card` class combines a suite with a face value. The `Player` class aggregates `Card` objects, illustrating composition over inheritance.

### Real-World Business Logic

[`Day31-35/code/example21.py`](https://github.com/jackfrued/Python-100-Days/blob/main/Day31-35/code/example21.py) applies OOP to a simple banking system. The script defines a bank account class with deposit and withdrawal methods, demonstrating how encapsulation protects internal state while exposing a clean public interface for financial transactions.

## Summary

- The **Python-100-Days** repository teaches OOP across **Days 31-35** using isolated, runnable scripts in `Day31-35/code/`.
- **Core pillars** are taught through concrete examples: encapsulation via the `Thing` class in [`example04.py`](https://github.com/jackfrued/Python-100-Days/blob/main/example04.py), inheritance through the `Employee` hierarchy in [`example12.py`](https://github.com/jackfrued/Python-100-Days/blob/main/example12.py), and polymorphism via uniform `get_salary()` implementations.
- **Advanced features** include custom iterators ([`example15.py`](https://github.com/jackfrued/Python-100-Days/blob/main/example15.py)), magic methods for collection compatibility ([`example16.py`](https://github.com/jackfrued/Python-100-Days/blob/main/example16.py)), multiple inheritance with MRO analysis ([`example17.py`](https://github.com/jackfrued/Python-100-Days/blob/main/example17.py)), and metaclasses for the Singleton pattern ([`example18.py`](https://github.com/jackfrued/Python-100-Days/blob/main/example18.py)).
- **Design patterns** such as Factory ([`example12.py`](https://github.com/jackfrued/Python-100-Days/blob/main/example12.py)) and practical domain modeling ([`example14.py`](https://github.com/jackfrued/Python-100-Days/blob/main/example14.py), [`example21.py`](https://github.com/jackfrued/Python-100-Days/blob/main/example21.py)) bridge the gap between theory and real-world application.

## Frequently Asked Questions

### How does Python-100-Days structure its OOP curriculum compared to other Python courses?

Unlike courses that introduce classes briefly and move on, Python-100-Days dedicates **five full days** (Days 31-35) to OOP, with each day building incrementally. The repository uses **single-concept files**—such as [`example04.py`](https://github.com/jackfrued/Python-100-Days/blob/main/example04.py) for encapsulation and [`example17.py`](https://github.com/jackfrued/Python-100-Days/blob/main/example17.py) for multiple inheritance—allowing learners to modify and run isolated examples without navigating complex project structures.

### What design patterns are implemented in the Day 31-35 code examples?

The repository demonstrates several **Gang of Four** patterns through practical Python implementations. The **Factory Method** pattern appears in [`example12.py`](https://github.com/jackfrued/Python-100-Days/blob/main/example12.py) via `EmployeeFactory.create()`, which decouples object instantiation from business logic. The **Singleton** pattern is enforced through a custom metaclass in [`example18.py`](https://github.com/jackfrued/Python-100-Days/blob/main/example18.py). Additionally, **mix-ins** in [`example17.py`](https://github.com/jackfrued/Python-100-Days/blob/main/example17.py) demonstrate a pattern for adding reusable functionality to existing classes.

### How does the repository teach Python-specific OOP features like magic methods and iterators?

Python-100-Days dedicates specific files to Python's **data model** features. [`example15.py`](https://github.com/jackfrued/Python-100-Days/blob/main/example15.py) teaches the **iterator protocol** by implementing `__iter__` and `__next__` in `PrimeIter` and `FibIter` classes. [`example16.py`](https://github.com/jackfrued/Python-100-Days/blob/main/example16.py) covers **magic methods** for collection integration, with `Student` implementing `__hash__` and `__eq__` for set/dict compatibility, and `School` implementing `__getitem__` and `__setitem__` for dictionary-like behavior.

### Where can I find examples of multiple inheritance and metaclasses in the repository?

Advanced inheritance concepts are covered in the final files of the OOP section. [`Day31-35/code/example17.py`](https://github.com/jackfrued/Python-100-Days/blob/main/Day31-35/code/example17.py) demonstrates **multiple inheritance** and **Method Resolution Order (MRO)** using classes A, B, C, and D, along with a practical `SetOnceMappingMixin` mix-in. [`Day31-35/code/example18.py`](https://github.com/jackfrued/Python-100-Days/blob/main/Day31-35/code/example18.py) introduces **metaclasses** through `SingletonMeta`, which controls class instantiation to enforce the Singleton pattern.