class St
Code Explanation:
1. Defining the class
class Store:
This line defines a class named Store.
A class is a blueprint used to create objects.
2. Class variable
items = []
items is a class variable, not an instance variable.
This list is shared by all objects created from the Store class.
There is only one items list in memory for the whole class.
3. Creating the first object
a = Store()
An object a is created from the Store class.
a does not get its own items list.
It refers to the same class-level items list.
4. Creating the second object
b = Store()
Another object b is created.
Just like a, it also refers to the same shared items list.
5. Appending an item
a.items.append(10)
a.items points to the class variable items.
append(10) adds 10 to the shared list.
Since the list is shared, all instances see this change.
6. Printing items from b
print(b.items)
b.items accesses the same shared list.
The list already contains 10.
So it prints:
[10]
Code Explanation:
items = []
a = Store()
b = Store()
a.items.append(10)
print(b.items)

0 Comments:
Post a Comment