Skip to content

Instantly share code, notes, and snippets.

@edwardbadboy
Created May 20, 2012 10:19
Show Gist options
  • Save edwardbadboy/2757575 to your computer and use it in GitHub Desktop.
Save edwardbadboy/2757575 to your computer and use it in GitHub Desktop.
useful Python code
import types
def foo(self, b):
print self._a
print b
class X(object):
def __init__(self):
self._a = 10
if __name__ == "__main__":
x = X()
x.foo = types.MethodType(foo, x)
x.foo(2)
__metaclass__ = type
class withme:
def __init__(self, avalue):
self.avalue=avalue
def getvalue(self):
return self.avalue
def __enter__(self):
print 'in', self.avalue
return self
def __exit__(self, ExceptType, ExceptObj, Traceback):
print 'out', self.avalue
if ExceptType is not None:
print 'Exception: type %r obj %r\n Trace: %r' % (ExceptType, ExceptObj, Traceback)
return False # raise exception; return true to suppress exception
return True # this value is ignored if there is no exception
if __name__ == '__main__':
with withme(3) as i, withme(4) as j:
print i.getvalue(), j.getvalue()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment