0
0
Pythonprogramming~3 mins

Why Public attributes in Python? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could open any box and instantly grab what you want without asking for directions?

The Scenario

Imagine you have a box full of toys, and you want to let your friends play with any toy they want. But you have to tell each friend exactly where each toy is inside the box every time they ask.

The Problem

This is slow and confusing because you have to remember and explain the exact location of every toy. If you add or move toys, you have to update all your instructions. It's easy to make mistakes or forget something.

The Solution

Public attributes let you label each toy clearly on the box so your friends can grab any toy directly without asking you. This makes sharing simple and fast, and you don't have to explain where everything is every time.

Before vs After
Before
class ToyBox:
    def __init__(self):
        self._toy1 = 'Car'

    def get_toy1(self):
        return self._toy1
After
class ToyBox:
    def __init__(self):
        self.toy1 = 'Car'

box = ToyBox()
print(box.toy1)
What It Enables

It allows easy and direct access to an object's data, making your code simpler and more readable.

Real Life Example

Think of a car object where you can directly check its color or model without asking the car to tell you through special methods every time.

Key Takeaways

Public attributes let you access object data directly.

This makes code easier to write and understand.

It saves time compared to complicated access methods.