Created
December 22, 2020 00:13
-
-
Save josepsmartinez/ef7b3a6136dfb9e9013a23c2942fa469 to your computer and use it in GitHub Desktop.
Python @Property and @*.setter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Reference: https://www.programiz.com/python-programming/property | |
| class Dummy(): | |
| def __init__(self): | |
| self.msg = "oi" # it calls get and setter functions | |
| @property | |
| def msg(self): | |
| print("Getting...") | |
| return self._msg | |
| @msg.setter | |
| def msg(self, val): | |
| print("Setting...") | |
| if not hasattr(self, "_msg"): | |
| self._msg = val | |
| return self._msg | |
| d = Dummy() | |
| m1 = d.msg | |
| print(m1) | |
| d.msg = "tchau" # won't change attribute because of setter's logic | |
| m2 = d.msg | |
| print(m2) | |
| assert m1 == m2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment