Skip to content

Instantly share code, notes, and snippets.

@josepsmartinez
Created December 22, 2020 00:13
Show Gist options
  • Select an option

  • Save josepsmartinez/ef7b3a6136dfb9e9013a23c2942fa469 to your computer and use it in GitHub Desktop.

Select an option

Save josepsmartinez/ef7b3a6136dfb9e9013a23c2942fa469 to your computer and use it in GitHub Desktop.
Python @Property and @*.setter
# 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