Skip to content

Instantly share code, notes, and snippets.

@kvas-it
Last active April 20, 2016 12:40
Show Gist options
  • Save kvas-it/a6d47179385d52a7be1218d38650e411 to your computer and use it in GitHub Desktop.
Save kvas-it/a6d47179385d52a7be1218d38650e411 to your computer and use it in GitHub Desktop.
Demonstrate how __getattr__ and __setattr__ interact with slots and normal properties. The interesting part is that if a slot is not assigned a value, __getattr__ will be called for it as for normal attributes.
# Demonstrate when __getattr__ and __setattr__ get called for slots
# and normal attributes.
#
# The output is:
# a = Main(42)
# __setattr__(abc, 42) called
# a.abc: 42
# __getattr__(cba) called
# a.cba: None
# __getattr__(slot) called
# a.slot: None
# a.slot = 69
# __setattr__(slot, 69) called
# a.slot: 69
# a.__dict__: {'abc': 42}
from __future__ import print_function
class Base(object):
__slots__ = ('slot',)
class Main(Base):
def __init__(self, abc):
self.abc = abc
def __getattr__(self, name):
print(' __getattr__({}) called'.format(name))
return None
def __setattr__(self, name, value):
print(' __setattr__({}, {}) called'.format(name, value))
Base.__setattr__(self, name, value)
if __name__ == '__main__':
print('a = Main(42)')
a = Main(42)
print('a.abc:', a.abc)
print('a.cba:', a.cba)
print('a.slot:', a.slot)
print('a.slot = 69')
a.slot = 69
print('a.slot:', a.slot)
print('a.__dict__:', a.__dict__)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment