Code Explanation:
1. Class Definition
class Box:
This line defines a class named Box.
A class is a blueprint for creating objects.
2. Constructor Method
def __init__(self, items=[]):
__init__ is the constructor, automatically called when a new object is created.
items=[] is a default argument.
⚠️ Important: This default list is created once, not every time a new object is made.
3. Instance Variable Assignment
self.items = items
self.items becomes an instance variable.
It refers to the same list object provided by items.
Because items is a shared default list, all objects without their own list will share it.
4. Creating First Object
b1 = Box()
A new Box object b1 is created.
No list is passed, so it uses the default list.
5. Creating Second Object
b2 = Box()
Another Box object b2 is created.
It also uses the same default list as b1.
6. Modifying the List via First Object
b1.items.append(10)
10 is added to the shared list.
Since both b1.items and b2.items point to the same list, the change affects both.
7. Printing Second Object’s List
print(b2.items)
Output will be:
[10]

0 Comments:
Post a Comment