3

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.

1
  • 1
    Why the "fullname" isn't showing up in the Dict even when I am assigning? The same reason why __init__ doesn't show up in the __dict__. It's method of your class. It's just decorated with @property which makes it look like an attribute but it is not an attribute. Commented Dec 12, 2020 at 19:07

1 Answer 1

5

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} 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.