Created
May 20, 2012 10:19
-
-
Save edwardbadboy/2757575 to your computer and use it in GitHub Desktop.
useful Python code
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
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) |
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
__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