Created
June 9, 2022 17:04
-
-
Save StephenFordham/78eb5d9bbb26df7d74069bb933eccbf4 to your computer and use it in GitHub Desktop.
__setattr__magic_method
This file contains hidden or 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
class Employees(object): | |
def __init__(self, name, age, location): | |
self._name = name | |
self._age = age | |
self._location = location | |
def __setattr__(self, key, value): | |
if key in ['_name', '_location']: | |
if not isinstance(value, str): | |
raise TypeError('Only valid attributes of type string are accepted') | |
else: | |
self.__dict__[key] = value | |
else: | |
self.__dict__[key] = value | |
e1 = Employees('stephen', 30, 'Bournemouth') | |
for key, value in e1.__dict__.items(): | |
print('{}: {}'.format(key, value)) | |
# Console Output | |
_name: stephen | |
_age: 30 | |
_location: Bournemouth |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment