Skip to content

Instantly share code, notes, and snippets.

@htv2012
Last active August 29, 2015 14:19
Show Gist options
  • Save htv2012/95063d7742b52b6cf3bd to your computer and use it in GitHub Desktop.
Save htv2012/95063d7742b52b6cf3bd to your computer and use it in GitHub Desktop.
Demo: a object that, after close, is in an invalid state. At this point, any method invocation will result in an exception. Output: http://codepad.org/34k4e7wB
class Foo(object):
def __invalid_action(self, *args, **kwargs):
raise IOError('Sorry, we are closed')
def __init__(self):
print 'create'
def read(self):
print 'read'
def close(self):
print 'close'
print '---'
for attr in dir(self):
if attr.startswith('_'):
continue
obj = getattr(self, attr)
if not callable(obj):
continue
setattr(self, attr, self.__invalid_action)
f = Foo()
f.read()
f.close()
f.read()
# Output: http://codepad.org/34k4e7wB
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment