Skip to content

Instantly share code, notes, and snippets.

@StephenFordham
Created June 9, 2022 18:08
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/f1bf6a58cea7868e0f971073859e867a to your computer and use it in GitHub Desktop.
Save StephenFordham/f1bf6a58cea7868e0f971073859e867a to your computer and use it in GitHub Desktop.
init_constructor_decorator
# __init__ method with a decorator
def attr_validation(method):
def inner(ref, name, age, location):
for attr in [name, location]:
if not isinstance(attr, str):
raise TypeError('Name and Location attributes must be of type str')
if not isinstance(age, int):
raise TypeError('Age attributes must be of type int')
return method(ref, name, age, location)
return inner
class Employees(object):
@attr_validation
def __init__(self, name, age, location):
self._name = name
self._age = age
self._locaton = location
# e1 = Employees('stephen', 30, 'Bournemouth')
e1 = Employees('stephen', '30', 'Bournemouth')
for key, value in e1.__dict__.items():
print('{}: {}'.format(key, value))
# Console Output
TypeError: Age attributes must be of type int
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment