Last active
July 7, 2020 19:16
-
-
Save StephenFordham/74f27d99e6b414fb7bbdebeb415d350a to your computer and use it in GitHub Desktop.
setattr_and_delattr
This file contains 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
# 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