Printing the arguments of an attribute in a class

Arnaud Delobelle arnodel at googlemail.com
Sun Feb 28 12:51:44 EST 2010


vsoler <vicente.soler at gmail.com> writes:

> I have a class that is a wrapper:
>
> class wrapper:
>     def __init__(self, object):
>         self.wrapped = object
>     def __getattr__(self, attrname):
>         print 'Trace: ', attrname
>         #print arguments to attrname, how?
>         return getattr(self.wrapped, attrname)
>
> I can run it this way:
>
>>>> x = wrapper([1,2,3])
>>>> x.append(4)
> Trace:  append
>>>> x.wrapped
> [1, 2, 3, 4]
>
> I am able to capture the attribute name to x (that is, append).
> However, I do not know how to capture and print all of its arguments
> (in this case number 4).
>
> How should I proceed?
>
> Thank you

You could do something like this:

class wrapper:
    def __init__(self, object):
        self.wrapped = object
    def __getattr__(self, attrname):
        print '** get attribute: ', self.wrapped, attrname
        return wrapper(getattr(self.wrapped, attrname))
    def __call__(self, *args, **kwargs):
        print '** call with args: ', self.wrapped, args, kwargs
        return wrapper(self.wrapped(*args, **kwargs))

x = wrapper([1,2,3])
x.append(4)

I haven't thought about it too much though.

-- 
Arnaud



More information about the Python-list mailing list