Printing the arguments of an attribute in a class
vicente.soler at gmail.com
Sun Feb 28 16:31:30 CET 2010
On Feb 28, 4:00 pm, "Alf P. Steinbach" <al... at start.no> wrote:
> * vsoler:
> > 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?
> If your goal is just learning then in your __getattr__ you might return a
> wrapper for the attribute instead of the attribute itself. Equip the wrapper
> with a __call__ method if it is a method. And equip it with other special
> methods as appropriate.
> I can imagine that that approach will lead to some practical problems, but it
> may be great for learning.
> If your goal is tracing, then I suggest looking at the "trace" module.
> If your goal is something else purely practical, like intercepting method calls
> to do arbitrary things (logging, marshaling, whatever) then I suspect that it
> might getspretty complicated, hairy. For specific method calls you might just
> use subclassing, but for doing this in general, parameterized, you'd need to
> about the same kinds of things as the trace module does. So I guess then one
> idea might be to look at the source code of that module.
> But if that's what you intend to do, then best check first if there is an
> existing solution. ParcPlace did this thing for a number of languages and
> introduced a special term for it, I can't recall but something like
> "cross-whatever mumbo jumbo concerns" plus one single catchy name. There might
> be an existing Python implementation.
> Cheers & hth.,
> - Alf
My goal is just learning. In the code provided in the post I just
can't think of a method to "see", "capture" or "use" the parameters. I
am going to study the __call__ method and see if I can figure out how
I can capture the parameters.
Thank you Alf
More information about the Python-list