Skip to content

Instantly share code, notes, and snippets.

@kmmbvnr
Last active June 22, 2016 10:50
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 kmmbvnr/53fe9b92a4d7c3703cbb to your computer and use it in GitHub Desktop.
Save kmmbvnr/53fe9b92a4d7c3703cbb to your computer and use it in GitHub Desktop.
Little python quiz
"""
Implement @secret_decorator allows to bypass decorator on base class method
"""
class Base(object):
@secret_decorator
def method(self):
print('base')
class Child(Base):
@secret_decorator
def method(self):
print('child')
# bypass super/secret_decorator and directly call method impl
super(Child, self).method.original()
"""
>>> base, child = Base(), Child()
>>> base.method()
decorated
base
>>> child.method()
decorated
child
base
"""
@sureshvv
Copy link

    def secret_decorator(func):
        def inner(self):
            print 'decorated'
            func(self)

        from functools import partial
        class Desc(object):
            def __init__(self, func): self.func = func
            def __call__(self): self.func(self)
            def __get__(self, instance): return partial(self.func, instance)

        inner.original = Desc(func)
        return inner

@kmmbvnr
Copy link
Author

kmmbvnr commented Jun 22, 2016

btw @sureshvv the solution contains a bug. In case of child.method() the self inside of base.method is not Child instance, but Desc instance

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment