Return class.

Chris Angelico rosuav at gmail.com
Sat Jul 26 20:40:19 CEST 2014


On Sun, Jul 27, 2014 at 4:29 AM, Satish ML <satishmlwizpro at gmail.com> wrote:
> What does "return Wrapper" do in the following piece of code? Which method does it invoke?
> I mean "return Wrapper" invokes __init__ method?
>
> def Tracer(aClass):
>     class Wrapper:
>         def __init__(self, *args, **kargs):
>             self.fetches = 0
>             self.wrapped = aClass(*args, **kargs)
>         def __getattr__(self, attrname):
>             print('Trace: ' + attrname)
>             self.fetches += 1
>             print(self.fetches)
>             return getattr(self.wrapped, attrname)
>     return Wrapper
>

It doesn't invoke anything. It returns the class itself - a callable,
subclassable thing, which wraps the passed-in class. When it's used as
a decorator, what happens is that first the basic class gets
constructed, then it gets passed to this function, and whatever this
function returns becomes the resulting class. So, taking the simplest
example:

@Tracer
class Spam:
    def __init__(self, *args):
        print(*args)
    def display(self):
        print('Spam!' * 8)

This is like doing this:

class Spam:
    def __init__(self, *args):
        print(*args)
    def display(self):
        print('Spam!' * 8)
Spam = Tracer(Spam)

And then Tracer begins executing, with the Spam class as "aClass". It
constructs a new class with two methods: an __init__ which passes
everything through to the wrapped class and retains the resulting
object, and a __getattr__ which proxies through to the original with
tracing facilities.

But all it does is construct and return that class. It doesn't call
anything, yet. Calling the class (instantiating an object of it)
happens when the Spam("CARST") call happens; instead of calling the
original Spam class, it calls the special wrapper, which then calls on
the original.

You can look up class decorators in the Python docs; they're not
something you'll use often (and they're something you'll write even
less often), but they can give you a lot of flexibility.

ChrisA



More information about the Python-list mailing list