Last active
August 29, 2015 13:57
-
-
Save dutc/9423330 to your computer and use it in GitHub Desktop.
This file contains 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
#!/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