Code Explanation:
1. Defining the Class
class User:
A class named User is defined.
It represents a user object that will store an age value.
2. Constructor Method (__init__)
def __init__(self):
self._age = 20
__init__ runs automatically when a User object is created.
It creates an instance variable _age and sets it to 20.
The single underscore (_age) is a convention meaning “internal/private variable”.
3. Defining a Property Getter
@property
def age(self):
return self._age
@property turns the method age() into a read-only attribute.
So instead of calling u.age(), you can write u.age.
It returns the value of _age.
4. Creating an Object
u = User()
A User object is created.
The constructor sets u._age = 20.
5. Accessing the Property
print(u.age)
u.age calls the property method age().
The method returns self._age, which is 20.
print prints that value.
6. Final Output
20
Final Answer
✔ Output:
20
✔ Reason:
The @property decorator allows age to be accessed like an attribute while actually calling a method that returns _age.


0 Comments:
Post a Comment