19. Problem to create a class with property decorator in Python

In this Python oops program, we will create a class with a property decorator in Python. This example demonstrates the use of properties in Python to control the access and modification of attributes.

Class with property decorator in Python

Steps to solve the program
  1. The MyClass class has an attribute _my_property which is initially set to None in the constructor (__init__ method).
  2. The @property decorator is used to define a getter method for the my_property attribute. This allows accessing _my_property as if it were a regular attribute of the class.
  3. The @my_property.setter decorator is used to define a setter method for the my_property attribute. This allows modifying the value of _my_property through assignment.
  4. An instance of the MyClass class is created.
    The my_property attribute is accessed as if it were a regular attribute, and a value of “Hello” is assigned to it.
  5. Behind the scenes, the setter method associated with the property is called.
  6. The print statement then accesses the my_property attribute, which triggers the getter method to retrieve the value of _my_property. The value “Hello” is printed.

				
					class MyClass:
    def __init__(self):
        self._my_property = None
    
    @property
    def my_property(self):
        return self._my_property
    
    @my_property.setter
    def my_property(self, value):
        self._my_property = value

# Create an object of the class
obj = MyClass()

# Access the property
obj.my_property = "Hello"
print(obj.my_property)
				
			

Output:

				
					Hello
				
			

Related Articles

Python Class Structure for Employee Management Application.

Python Class structure with module-level Import.

Leave a Comment