Code Explanation:
1. Class Definition
class Person:
This defines a new class named Person.
A class is a blueprint for creating objects.
Each object of this class can have its own attributes like name, age, etc.
2. Constructor Method
def __init__(self, name):
self.name = name
__init__ is the constructor method in Python.
It runs automatically when a new object of Person is created.
name is a parameter passed during object creation.
self.name = name assigns the value of name to the object’s attribute name.
3. Creating an Object
p = Person("Alice")
This creates an object p of class Person.
The constructor is called with name = "Alice".
The object now has an attribute p.name = "Alice".
4. Adding a Dynamic Attribute
p.age = 25
Here, a new attribute age is added dynamically to the object p.
Python allows adding attributes outside the constructor.
Now, p has two attributes: name = "Alice" and age = 25.
5. Accessing the Dynamic Attribute
print(p.age)
Accessing p.age retrieves the dynamically added attribute.
Python prints the value of age, which is:
Final Output:
25
.png)

0 Comments:
Post a Comment