-2

I have declared the following class and declared email as a property which is initialized with property decorators.however the __dict__ does not list email as the property of the object rather lists _email. How is this working?

class abc:
    def __init__(self,first,second):
        self.first=first
        self.second=second
        self.email=first+","+second
    @property
    def email(self):
        return self._email
    @email.setter
    def email(self,e):
        self._email=e
        
a = abc("hello","world")
print(a.first)
print(a.second)
print(a.email)
print(a.__dict__)
2
  • The property is on the class, only the backing attribute is in the instance dictionary. Commented May 30, 2021 at 11:44
  • @jonrsharpe can you elaborate please Commented May 30, 2021 at 11:57

1 Answer 1

-1

This is what sets the attribute and hence why it shows _email:

@email.setter
def email(self,e):
    self._email=e
        

This setter function is called when you write:

self.email=first+","+second

Which is like writing:

email(first+","+second)

And then results in:

self._email=first+","+second

Lastly, when we refer to self.email, we are essentially calling the getter:

@property
def email(self):
    return self._email

However, when we refer to self._email, we are accessing the backing attribute without calling the 'getter'. This is why it makes sense to distinguish between _email and email, and why it specifies _email in the dict.

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.