Skip to content

Instantly share code, notes, and snippets.

@StephenFordham
Created June 9, 2022 17:04
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/78eb5d9bbb26df7d74069bb933eccbf4 to your computer and use it in GitHub Desktop.
Save StephenFordham/78eb5d9bbb26df7d74069bb933eccbf4 to your computer and use it in GitHub Desktop.
__setattr__magic_method
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