Search code examples
pythonooppython-decorators

__dict__ for an object not showing @property attribute


When using decorators, I am setting an attribute through "setter" decorator, however it doesn't show up in object's dict. Below is my code

class Employee:
    def __init__(self, first, last):
        self.f_name = first
        self.l_name = last
        self.email = self.f_name + '.' + self.l_name + '@hotmail.com'
    
    @property
    def fullname(self):
        return ('{} {}'.format(self.f_name,self.l_name) )


    @fullname.setter
    def fullname(self, name):
        first, last = name.split(' ')
        self.f_name = first
        self.l_name = last
        self.email = self.f_name + '.' + self.l_name + '@hotmail.com'
        
emp_1 = Employee('Sandeep', 'Behera')
print(emp_1.__dict__)


emp_1.fullname = "Alex Smith"
print(emp_1.__dict__)

emp_1.age = 20
print(emp_1.__dict__)

Running above, the result is :

{'f_name': 'Sandeep', 'l_name': 'Behera', 'email': '[email protected]'}
{'f_name': 'Alex', 'l_name': 'Smith', 'email': '[email protected]'}
{'f_name': 'Alex', 'l_name': 'Smith', 'email': '[email protected]', 'age': 20}

Why the "fullname" isn't showing up in the Dict even when I am assigning

emp_1.fullname = "Alex Smith"

but it shows "age" attribute. Does it have to do something with decorators? Thanks in advance.


Solution

  • Your decorated setter does not create an attribute fullname. Adding a new line to your setter as follows will give you an attribute full_name:

    @fullname.setter
    def fullname(self, name):
        first, last = name.split(' ')
        self.f_name = first
        self.l_name = last
        self.email = self.f_name + '.' + self.l_name + '@hotmail.com'
        self.full_name = name      # creating an attribute full_name
    

    The result is as follows:

    {'f_name': 'Sandeep', 'l_name': 'Behera', 'email': '[email protected]'}
    {'f_name': 'Alex', 'l_name': 'Smith', 'email': '[email protected]', 'full_name': 'Alex Smith'}
    {'f_name': 'Alex', 'l_name': 'Smith', 'email': '[email protected]', 'full_name': 'Alex Smith', 'age': 20}