decorat{or,ion}

dieter dieter at handshake.de
Sat May 19 02:22:59 EDT 2018


Mike McClain <mike.junk.46 at att.net> writes:
>     Let's say I want something that does most or all of foo's
> functionality plus a little more and maybe tweek some of foo's
> output, so I write a wrapper around foo and call it bar.
> If inside bar are the call to foo, as well as methods baz(),
> buz() and bug() that make their magic and bar ends up performing
> as I want.
>
>     If I understood correctly baz(), buz() and bug() plus the glue
> that is bar are decorations around foo or bar is a decorator of foo.

Maybe. I have never had need to speak of a "decoration".
My feeling tends more to use this term for the syntactic
construct ("@<decorator>[(args)]<function>") then the implementation
details of the decorator ("bar" in your example).

>     Apologies, I don't yet know how to show that foo and bar are
> meant to be objects.

No need to force yourself to view them as "object"s.

An "object", in general, is something that can have attributes
(holding the object state) and methods (defining often operations on
the object state but in some cases also general operations (not
related to the object state).
In this sense, almost everything you handle in a Python script
can be view as an object (an exception are the variables;
they, themselves, are not objects but their values are objects).

In your example, "foo" and "bar" are functions.
As such, they are also objects - but the feature (attributes,
methods) is rarely used explicitely (you can use
"dir(<your function>)" to learn what attributes and methods
your function has). You use functions in Python typically as
you are used to use them in another programming language.


> ...
>     For that matter, are baz(), buz() and bug() methods if they only
> help bar get the job done but don't have a place in bar's interface?

Your functions are methods, if they are defined inside a class.

Typically (there are exceptions), this means that their definition
occurs at the top level of a "class" statement:

       class CLS...:
         ...
         def method(self, ...):
           ...

       In this case, "method" is a method of class "CLS"
       and its instances (called "CLS" objects).

When you access a method of an object, then
the function representing the method is wrapped;
the wrapper remembers the object and the function and
ensures that the object is automatically passed as
the first parameter of the function ("self" in the example above)
in method calls.
Thus, the distinction between a method and a "normal" function
is that for a method, the first parameter is passed automatically
while in a "normal" function, the call must pass all arguments explicitly.




More information about the Python-list mailing list