Code Explanation:
1. Defining the Class Temperature
class Temperature:
This line defines a class named Temperature
The class is used to represent a temperature object
2. Constructor Method __init__
def __init__(self):
self._celsius = 25
__init__ is the constructor
It runs automatically when an object is created
self._celsius is an instance variable
The single underscore _ indicates:
This variable is intended to be protected (by convention)
The value 25 is stored in _celsius
3. Using the @property Decorator
@property
def celsius(self):
return self._celsius
@property converts the method celsius() into a read-only attribute
This allows access like a variable, not like a function
Instead of writing:
temp.celsius()
we can write:
temp.celsius
The method returns the value of _celsius
4. Creating an Object
temp = Temperature()
An object temp of class Temperature is created
The constructor sets _celsius = 25
5. Accessing the Property
print(temp.celsius)
temp.celsius internally calls the method celsius()
The returned value (25) is printed
6. Final Output
25
Final Answer
Output:
25


0 Comments:
Post a Comment