How does the property decorator work in Python with example explained

    By: Manu
    5 months ago

    Ok property decorators are used so that you can define a method as a "getter" for a class attribute, In simple words you can access methods as attributes rather than methods. Have look in this example.


    Getter Example

    class Main:
    
    
        def __init__(self, name):
            self._name = name
    
    
        @property
        def name(self):
            return self._name
        
    obj =  Main("Roger")
    print(obj.name)
    


    This outputs the name "Roger", But note inside print we are calling name as attribute


    Setter Example


    class Main:
    
    
        def __init__(self, name):
            self._name = name
    
    
        @property
        def name(self):
            return self._name
        
        @name.setter
        def name(self, new_name):
            self._name = new_name
        
    obj =  Main("Roger")
    obj.name = "Manu"
    print(obj.name)
    


    Here we are using setter and then later setting name as "Manu", which outputs as Manu.


    Deleter Example


    class Main:
    
    
        def __init__(self, name):
            self._name = name
    
    
        @property
        def name(self):
            return self._name
        
        @name.setter
        def name(self, new_name):
            self._name = new_name
    
    
        @name.deleter
        def name(self):
            del self._name
        
    obj =  Main("Roger")
    obj.name = "Manu"
    del obj.name
    print(obj.name)
    


    Here print gives an error "AttributeError: 'Main' object has no attribute '_name'. Did you mean: 'name'"


    But if we change code before print like

    obj =  Main("Roger")
    obj.name = "Manu"
    #del obj.name
    print(obj.name)
    


    Now we get output as "Manu". As delete is not deleting the value.