-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__)
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
user2779311
  • 1,688
  • 4
  • 23
  • 31

1 Answers1

-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.

Sentinel
  • 261
  • 1
  • 8