Skip to content

Instantly share code, notes, and snippets.

@dutc
Last active August 29, 2015 13:57
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 dutc/9423330 to your computer and use it in GitHub Desktop.
Save dutc/9423330 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
# using inspect
from inspect import currentframe, getframeinfo
class Foo:
def __init__(self, quux):
self.quux = quux
def bar(self):
return getframeinfo(currentframe()).function, self.quux
assert Foo('spam').bar() == ('bar', 'spam')
# using __getattr__
class Foo:
def __init__(self, quux):
self.quux = quux
def __getattr__(self, attr):
if attr == 'bar':
def bar():
# self bound via closure
return attr, self.quux
return bar
return super().__getattribute__(self, attr)
assert Foo('spam').bar() == ('bar', 'spam')
# using a descriptor
class Foo:
def __init__(self, quux):
self.quux = quux
class bar:
def __get__(descr, self, instance):
def bar():
# self bound via closure
return type(descr).__name__, self.quux
return bar
bar = bar()
assert Foo('spam').bar() == ('bar', 'spam')
# using a decorator
from functools import wraps
def dec(func):
@wraps(func)
def wrapped(*args, **kwargs):
rv = func(*args, **kwargs)
return func.__name__, rv
return wrapped
class Foo:
def __init__(self, quux):
self.quux = quux
@dec
def bar(self):
return self.quux
assert Foo('spam').bar() == ('bar', 'spam')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment