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
- The MyClass class has an attribute _my_property which is initially set to None in the constructor (__init__ method).
- 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.
- 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.
- 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. - Behind the scenes, the setter method associated with the property is called.
- 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
Write a Python Class structure with module-level Import.
Create 5 different Python Classes and access them via a single class object.
Create 5 Python classes and set up multilevel inheritance among all the classes.
Set Instance variable data with setattr and getattr methods.
Python oops program with encapsulation.