Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Three possible ways to implement the descriptor protocol in Python.
import re
class User(object):
def __init__(self):
self._phone_number = ''
@property
def phone_number(self):
return self._phone_number
@phone_number.setter
def phone_number(self, value):
if re.match(r'^(\d{3})-(\d{3})-(\d{4})', value):
print('Adding phone number for user: {}'.format(value))
self._phone_number = value
else:
raise ValueError('Phone Number format does not match.')
@phone_number.deleter
def phone_number(self):
print("Deleting: {}".format(self._phone_number))
del self._phone_number
if __name__ == '__main__':
py_user = User()
py_user.phone_number
py_user.phone_number = '800-123-4567'
del py_user.phone_number
import re
class PyDescriptor(object):
def __init__(self):
self._name = None
def __get__(self, instance, owner):
print("Getting: {}".format(self._name))
return self._name
def __set__(self, instance, value):
print("Setting: {}".format(self._name))
print("To value: {}".format(value))
self._name = value
def __delete__(self, instance):
print("Deleting: {}".format(self._name))
del self._name
class User(object):
name = PyDescriptor()
if __name__ == '__main__':
py_user = User()
py_user.name
py_user.name = 'Harry'
del py_user.name
import re
class User(object):
def __init__(self):
self._phone_number = ''
def fget(self):
return self._phone_number
def fset(self, value):
if re.match(r'^(\d{3})-(\d{3})-(\d{4})', value):
print('Adding phone number for user: {}'.format(value))
self._phone_number = value
else:
raise ValueError('Phone Number format does not match.')
def fdel(self):
print("Deleting: {}".format(self._phone_number))
del self._phone_number
phone_number = property(fget, fset, fdel, 'I am the phone number property.')
if __name__ == '__main__':
user = User()
user.phone_number = '123'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.