Properties in Python

  • The @property built-in decorator is used to create the properties on any method in the class.
  • @property is used to declare the method as a property.
  • @property-name.setter is used for the setter method which sets the value to a property
  • @property-name.deleter is used for the delete method which deletes a property.
class Courses:
    def __init__(self, courseName):
        self.__courseName = courseName  #private instance variable
   
    @property   # Declaring the method as Property
    def courseName(self):
        return self.__courseName
    
    @courseName.setter  #Property Setter which sets the value to a property
    def courseName(self,updatedValue):
        self.__courseName = updatedValue
      
    @courseName.deleter   
    def courseName(self):
        del self.__courseName
  • Above, @property decorator applied to the courseName() method. The courseName() method returns the private instance attribute value __courseName.
  • To modify the property value, we have defined the setter method for the courseName property using @property-name.setter decorator. The setter method takes the updatedValue argument that is used to assign the private attribute value.
  • Use the @property-name.deleter decorator for the method that deletes a property. The deleter would be automatically called when you delete the property using keyword del.

References:

  • https://docs.python.org/3/howto/descriptor.html
  • https://docs.python.org/3/library/functions.html

Learn more about Python Features in the upcoming blog articles.

Happy Learning!