Methods are functions that are called using the attribute notation. There are two flavors: built-in methods (such as append() on lists) and class instance methods. Built-in methods are described with the types that support them.
The implementation adds two special read-only attributes to class
instance methods: m.im_self
is the object on which the
method operates, and m.im_func
is the function
implementing the method. Calling m(arg-1,
arg-2, ..., arg-n)
is completely equivalent to
calling m.im_func(m.im_self, arg-1,
arg-2, ..., arg-n)
.
Class instance methods are either bound or unbound,
referring to whether the method was accessed through an instance or a
class, respectively. When a method is unbound, its im_self
attribute will be None
and if called, an explicit self
object must be passed as the first argument. In this case,
self
must be an instance of the unbound method's class (or a
subclass of that class), otherwise a TypeError
is raised.
Like function objects, methods objects support getting and setting
arbitrary attributes. However, the attributes are actually stored on
the underlying function object (i.e. meth.im_func
). To avoid
surprising behavior, a TypeError
is raised when an attempt is
made to set an attribute on a bound method. It is legal to get a
bound method's attribute (the underlying function's attribute is
returned), and it is also legal to set or get an unbound method's
attribute. For example:
class C: def method(self): pass c = C() d = C() c.method.whoami = 'my name is c' d.method.whoami = 'my name is d'
If bound method attribute setting was allowed, c.method.whoami
would return ``my name is d''.
See the Python Reference Manual for more information.
See About this document... for information on suggesting changes.