How To Use Property Function / Decorator In Python

If you want to add an attribute to python class, you can use property() function or @property decorator. The two method all has advantages and disadvantages, and the goal of using that is to make code simple. After you define class attribute with property() function or @property decorator, your client code can invoke the class attribute directly. If you do not change the attribute name, you can change the attribute implementation at any time and the client code that invoke the attribute do not need to change.

1. Use Property Function.

  1. To declare a python class attribute, you should follow below syntax.
    attribute_name = property(get_attr_value_function, set_attr_value_function, delete_attr_value_function, doc_string)
  2. Below is an example.
    '''
    @author: zhaosong
    '''
    
    class UserAccount:
        
        def __init__(self, user_name, password, email):
            # _user_name, _password, _email are private variables.
            self._user_name = user_name
            self._password = password
            self._email = email
        
        # define private method prefixed with single _
        def _get_user_name(self):
            print('get_use_name, value is : ' + self._user_name)
            return self._user_name
        
        def _set_user_name(self, user_name):
            print('set_use_name, to new value : ' + user_name)
            self._user_name = user_name
            
        def _delete_user_name(self):    
            print('delete_use_name.')
            del self._user_name
            
        # declare account_user_name as a property of UserAccount class, and assign above three methods to the property function arguments.
        account_user_name = property(_get_user_name, _set_user_name, _delete_user_name, 'This property is account_user_name')
    
    
    if __name__ == '__main__':
        
        user = UserAccount(user_name='Jerry', password='Jerry', email='jerry@dev2qa.com')
        
        # call the class object attribute directly, this will invoke UserAccount private function _get_user_name .
        user.account_user_name
        
        # set the class object attribute to invoke UserAccount private _set_user_name function.
        user.account_user_name = 'Tom'
        
        user.account_user_name
        
        # Invoke UserAccount._delete_user_name function.
        del user.account_user_name
        
    

2. Use @Property Decorator.

  1. You should note below three point when you use @property decorator.
  2. The @property decorator decorated method name is the class attribute name. And this method also implement the get function of the attribute.
    @property
    def account_user_name(self):
        ......
  3. The set and delete method name is same with the get method name, and decorate them with @attribute_name.setter (@account_user_name.setter) and @attribute_name.deleter (@account_user_name.deleter).
    @account_user_name.setter
    def account_user_name(self, user_name):
        ......      
        
    @account_user_name.deleter 
    def account_user_name(self):
        ......
  4. If the three method name is not same, you will get below errors.
    AttributeError: can't set attribute
    
    or
    
    AttributeError: can't delete attribute
  5. Below is the example full source code.
    class UserAccount:
        
        def __init__(self, user_name, password, email):
            # _user_name, _password, _email are private variables.
            self._user_name = user_name
            self._password = password
            self._email = email
        
        @property
        def account_user_name(self):
            print('get_use_name, value is : ' + self._user_name)
            return self._user_name
        
        @account_user_name.setter
        def account_user_name(self, user_name):
            print('set_use_name, to new value : ' + user_name)
            self._user_name = user_name
          
        @account_user_name.deleter 
        def account_user_name(self):    
            print('delete_use_name.')
            del self._user_name      
    
    if __name__ == '__main__':
        
        user = UserAccount(user_name='Jerry', password='Jerry', email='jerry@dev2qa.com')
        
        user.account_user_name
        
        user.account_user_name = 'Tom'
        
        user.account_user_name
        
        del user.account_user_name
  6. When you execute above code, you can get below output.
    get_use_name, value is : Jerry
    set_use_name, to new value : Tom
    get_use_name, value is : Tom
    delete_use_name.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.