Attack a sacred Python Cow

Terry Reedy tjreedy at
Mon Jul 28 07:32:13 CEST 2008

Derek Martin wrote:

> Furthermore, as you described, defining the function within the scope
> of a class binds a name to the function and then makes it a method of
> the class.  Once that happens, *the function has become a method*.

If you mean that a user-defined function object becomes a different 
class of object when bound to a class attribute name, that is wrong. 
Once a function, always a function.  It may be called an 'instance 
method' but it is still a function.  Any function object can be an 
attribute of multiple classes, without inheritance, or of none.

When a function attribute is accessed via an instance of the class, it 
is *wrapped* with a bound method object that basically consists of 
references to the function and instance.  When the 'bound method' is 
called, the instance is inserted in front of the other arguments to be 
matched with the first parameter.

In 2.0, functions accessed through the class were rather uselessly 
wrapped as an 'unbound method', but those wrappers have been discarded 
in 3.0.

> To be perfectly honest, the idea that an object method can be defined
> outside the scope of an object (i.e. where the code has no reason to
> have any knowledge of the object) seems kind of gross to me...

I happen to like the simplicity that "def statements (and lambda 
expressions) create function objects."  Period.

> It does indeed -- it does more than imply.  It states outright that
> the function is defined within the namespace of that object,


> and as such that it is inherently part of that object.

False.  That does not follow.  Python objects generally exist 
independently of each other.  Think of them as existing in a nameless 
dataspace if you want.  Collection/container objects collect/contain 
references to their members, just as a club roster does, but they only 
metaphorically 'contain' their members.  Any object can be a member of 
any number of collections, just as humans can join any number of clubs 
and groups.  In mathematical set theory, membership is also non-exclusive.

> So why should it need
> to be explicitly told about the object of which it is already a part?

Because it is not a 'part' of a class in the sense you seem to mean.

What is true is that functions have a read-only reference to the global 
namespace of the module in which they are defined.  But they do not have 
to be a member of that namespace.

Terry Jan Reedy

More information about the Python-list mailing list