Skip to content

Instantly share code, notes, and snippets.

@StephenFordham
Last active July 7, 2020 19:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StephenFordham/74f27d99e6b414fb7bbdebeb415d350a to your computer and use it in GitHub Desktop.
Save StephenFordham/74f27d99e6b414fb7bbdebeb415d350a to your computer and use it in GitHub Desktop.
setattr_and_delattr
# 1. using dunder __setattr__, __delattr__,
class Employees(object):
def __init__(self, name, age, service_length):
self._name = name
self._age = age
self._service_length = service_length
def __setattr__(self, key, value):
if key == '_name' and hasattr(self, '_name'):
raise AttributeError('This attribute can only be set once in the init method')
elif key == '_name':
self.__dict__[key] = value.title()
else:
if key == '_age' or key == '_service_length':
if not isinstance(value, int):
raise TypeError()
self.__dict__[key] = value
def __delattr__(self, key):
if key == '_name':
raise AttributeError('This attribute cannot be deleted')
else:
del self.__dict__[key]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment