Created
June 9, 2022 18:08
-
-
Save StephenFordham/f1bf6a58cea7868e0f971073859e867a to your computer and use it in GitHub Desktop.
init_constructor_decorator
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
# __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