Code Explanation:
1. Defining the Class
class Score:
- The class keyword defines a class named Score.
- A class acts as a blueprint for creating objects.
- This class demonstrates how to control attribute access using properties.
2. Initializing the Instance Variable
def __init__(self): self._n = 5
- __init__() runs automatically when a new Score object is created.
- self refers to the current object.
- self._n = 5 initializes the instance variable _n with the value 5.
- The underscore indicates that _n is intended for internal use by convention.
3. Applying the @property Decorator
@property
- The @property decorator allows a method to be accessed like an attribute.
- Instead of calling s.n(), you can simply write s.n.
- It is useful for calculating or controlling values when an attribute is accessed.
4. Defining the Getter Method
def n(self): return self._n * 2
- Defines the getter method for the property n.
- It reads the stored value of _n and multiplies it by 2.
- Initially, _n = 5, so accessing s.n returns 10.
5. Applying the @n.setter Decorator
@n.setter
- This decorator defines how assignments to the property n are handled.
- It allows you to write s.n = 8 and control what happens when that assignment occurs.
- The setter updates the underlying _n value.
6. Defining the Setter Method
def n(self, v): self._n = v
- The setter receives the assigned value through the parameter v.
- When s.n = 8 executes, v becomes 8.
- The statement updates self._n to 8.
- The getter will then use this updated value.
7. Creating an Object
s = Score()
- Creates an instance of the Score class.
- The initializer executes automatically.
- The initial value becomes s._n = 5.
8. Updating the Property
s.n = 8
- Assigns 8 to the property n.
- Python calls the setter method.
- The setter stores 8 in s._n.
- The stored value changes from 5 to 8.
9. Accessing and Printing the Property
print(s.n)
- Accesses the getter method through the property n.
- The getter calculates s._n * 2.
- Since s._n = 8, the result is 8 * 2 = 16.
- The print() function displays 16.
Final Output
16
Book: 100 Python Programs for Beginner with explanation


0 Comments:
Post a Comment