Python OOP Course


Python OOP Course

Anna
Alright, Michael, let's talk about object-oriented programming in Python. The tutorial we just went through starts with a store management system—tracking items like phones and laptops. Without OOP, you'd just use separate variables for each item's name, price, and quantity, but those aren't really connected.

Michael
Right, and the instructor points out that even though you name them with prefixes like `item1_name`, Python treats them as four unrelated variables. That's a mess when you have many items. So OOP lets you create your own data types that bundle related data together.

Anna
Exactly. You start by defining a class. In Python, it's as simple as `class Item: pass`. Then you create instances like `item1 = Item()`. That gives you a custom data type. You can dynamically assign attributes with dot notation: `item1.name = 'Phone'` and so on.

Michael
But that's still manual. What's the real difference? Well, when you print `type(item1)`, you see `<class '__main__.Item'>` instead of just `str` or `int`. So now you have a real custom type, and you can attach methods to it.

Anna
Methods are just functions inside a class. They always take `self` as the first parameter, because Python passes the instance itself when you call them. For example, a method `calculate_total_price` can access `self.price` and `self.quantity` and multiply them.

Michael
And the tutorial highlights a common mistake—forgetting `self` leads to a 'takes 0 positional arguments but 1 was given' error. So you must always include `self` (or any name, but convention is `self`).

Anna
Right. But manually assigning attributes for each instance is tedious. That's where the `__init__` method, the constructor, comes in. Python automatically calls it when you create an instance. You define `def __init__(self, name, price, quantity):` and inside assign `self.name = name`, etc.

Michael
So now when you do `item1 = Item('Phone', 100, 5)`, the constructor runs and sets those attributes. That's much cleaner. You can also give default values, like `quantity=0`, so it's optional.

Anna
And they also add type hints: `name: str`, `price: float`, `quantity: int`. Those help with clarity but don't enforce types at runtime. For validation, you can use `assert` statements, like `assert price >= 0`, to catch bugs early.

Michael
Now, let's talk about class attributes versus instance attributes. The `pay_rate` is set at the class level—like a 20% discount. Each instance can override it by setting its own `pay_rate`, but if it doesn't, Python looks up the class attribute. That lookup order is instance → class → parent classes.

Anna
And they demonstrate using `__dict__` to see which attributes are on the instance versus the class. That's handy for debugging. Then they build an `apply_discount` method that uses `self.pay_rate` so that individual instances can have different discount rates.

Michael
Another neat trick is the `__repr__` method. By default, printing a list of objects shows ugly `<Item object at 0x...>`. But if you define `def __repr__(self): return f"Item('{self.name}', {self.price}, {self.quantity})"`, then printing `Item.all` gives something readable—and you can even copy-paste it to recreate instances.

Anna
And speaking of `all`, they created a class attribute `all = []` and appended `self` in `__init__`. Now you have a list of all instances. That's useful for iterating or filtering. But to avoid hardcoding data in the code, they introduced CSV files.

Michael
Right. They use `@classmethod` to define `instantiate_from_csv`. A class method takes `cls` instead of `self` and can be called on the class itself, like `Item.instantiate_from_csv('items.csv')`. Inside, it uses the `csv` module to read the file and create instances.

Anna
They also define a `@staticmethod` called `is_integer`. Static methods don't receive `self` or `cls` automatically—they're just like regular functions but live in the class namespace. This one checks if a number is an integer, counting out floats that end with .0.

Michael
Now inheritance. You can have a `Phone` class that inherits from `Item`. In Python, you write `class Phone(Item):`. The child class gets all the parent's methods and attributes. But if the child needs extra attributes, you define its own `__init__` and call `super().__init__` to run the parent's constructor.

Anna
Exactly. For example, `Phone` might have `broken_phones` on top of `name, price, quantity`. By calling `super().__init__(name, price, quantity)`, you reuse the parent's validation and assignment. Without that, you'd have to duplicate code, which is bad practice.

Michael
And in `__repr__`, they use `self.__class__.__name__` instead of hardcoding 'Item'. That way, when a `Phone` instance is printed, it says 'Phone' instead of 'Item'. That's a nice touch for polymorphism.

Anna
Now let's dive into encapsulation. The tutorial shows how to make a read-only attribute using the `@property` decorator. For instance, they make `name` a property that returns a private attribute `_name`. Then they add a setter so that when you assign to `name`, it goes through validation—like checking the length.

Michael
And they use double underscore `__name` to make it truly private. Actually, Python mangles the name to `_ClassName__name`, so it's harder to access from outside. That's the Python way of encapsulation. They do the same for `price`—make it a property and then only modify it through methods like `apply_increment`.

Anna
Abstraction is about hiding internal complexity. They have a `send_email` method that internally calls private methods like `__connect`, `__prepare_body`, and `__send`. Those are prefixed with double underscore to mark them as private, so users of the class don't accidentally call them.

Michael
Then inheritance and polymorphism. You can create a `Keyboard` class that also inherits from `Item`. It can override class attributes like `pay_rate` to give keyboards a different discount. The `apply_discount` method uses `self.pay_rate`, so it picks up the subclass's value—that's polymorphism in action.

Anna
And polymorphism is everywhere in Python. The `len()` function works on strings, lists, tuples—it's a single interface that adapts to different types. In your own classes, if you implement `__len__`, then `len(instance)` will call your method.

Michael
So to sum up: OOP in Python gives you four pillars. Encapsulation—hiding data with properties and private attributes. Abstraction—hiding implementation details. Inheritance—reusing code from parent classes. And polymorphism—using a common interface across different types.

Anna
Exactly. The tutorial walks through building a real application step by step, and by the end, you have a solid foundation. I think the key takeaway is to start simple—define a class with `__init__`, use class attributes for shared data, and grow with inheritance and encapsulation as needed.

Ask anything
We've read this whole study set, so questions about it get the best answers.