Code Explanation:
class Slotted:
This defines a new class called Slotted.
At this point, it’s a regular Python class — no special behavior like __slots__ has been added.
def __init__(self):
This defines the constructor method (__init__) for the class.
It’s automatically called when you create a new object from this class.
The self parameter refers to the instance being created.
self.a = 10
Inside the constructor, a new instance attribute a is created and set to 10.
This means every object of this class will have an attribute a when it's initialized.
s = Slotted()
You create an instance of the class Slotted and store it in the variable s.
This automatically calls the __init__ method, so s.a is now 10.
s.b = 20
Here, you're dynamically adding a new attribute b to the instance s, and setting it to 20.
Because Slotted is a normal class (no __slots__), Python allows this dynamic addition.
print(s.a, s.b)
This prints the values of attributes a and b from the instance s.
Since s.a = 10 and s.b = 20, it prints:
10 20
0 Comments:
Post a Comment