Code Explanation;
1. Defining the Class
class Temperature:
- The class keyword defines a class named Temperature.
- A class acts as a blueprint for creating objects.
- Here, the class represents a temperature value.
2. Initializing the Object
def __init__(self, c): self.c = c
- __init__() is the initializer method that runs automatically when an object is created.
- self refers to the current object.
- c receives the value passed when creating the object.
- self.c = c stores that value as an instance attribute.
For example, Temperature(7) stores 7 in self.c.
3. Applying the @property Decorator
@property
- The @property decorator allows a method to be accessed like an attribute.
- It lets you calculate and return a value without calling the method with parentheses.
- This is useful for computed attributes.
4. Defining the fahrenheit Property
def fahrenheit(self): return self.c * 2
- Defines a method named fahrenheit.
- self.c accesses the stored temperature value.
- The method multiplies that value by 2 and returns the result.
- Since self.c = 7, the calculation is 7 * 2 = 14.
5. Creating the Object
t = Temperature(7)
- Creates an instance of the Temperature class.
- Passes 7 to the initializer.
- The value is stored in t.c.
6. Accessing the Property
print(t.fahrenheit)
- Accesses the fahrenheit property without parentheses.
- Python automatically executes the property method.
- The method calculates 7 * 2, returning 14.
- The print() function displays the result.
Final Output


0 Comments:
Post a Comment