Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit d4614e8

Browse files
committed
Updates to the semantics of function and method attributes.
1 parent ab354bb commit d4614e8

1 file changed

Lines changed: 18 additions & 14 deletions

File tree

Doc/lib/libstdtypes.tex

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -982,6 +982,16 @@ \subsubsection{Functions \label{typesfunctions}}
982982
function attributes on functions written in Python. Function
983983
attributes on built-ins may be supported in the future.}
984984

985+
Functions have another special attribute \code{\var{f}.__dict__}
986+
(a.k.a. \code{\var{f}.func_dict}) which contains the namespace used to
987+
support function attributes. \code{__dict__} can be accessed
988+
directly, set to a dictionary object, or \code{None}. It can also be
989+
deleted (but the following two lines are equivalent):
990+
991+
\begin{verbatim}
992+
del func.__dict__
993+
func.__dict__ = None
994+
\end{verbatim}
985995

986996
\subsubsection{Methods \label{typesmethods}}
987997
\obindex{method}
@@ -1007,29 +1017,23 @@ \subsubsection{Methods \label{typesmethods}}
10071017
\code{self} must be an instance of the unbound method's class (or a
10081018
subclass of that class), otherwise a \code{TypeError} is raised.
10091019

1010-
Like function objects, methods objects support getting and setting
1011-
arbitrary attributes. However, the attributes are actually stored on
1012-
the underlying function object (i.e. \code{meth.im_func}). To avoid
1013-
surprising behavior, a \code{TypeError} is raised when an attempt is
1014-
made to set an attribute on a bound method. It is legal to get a
1015-
bound method's attribute (the underlying function's attribute is
1016-
returned), and it is also legal to set or get an unbound method's
1017-
attribute. For example:
1020+
Like function objects, methods objects support getting
1021+
arbitrary attributes. However, since method attributes are actually
1022+
stored on the underlying function object (i.e. \code{meth.im_func}),
1023+
setting method attributes on either bound or unbound methods is
1024+
disallowed. Attempting to set a method attribute results in a
1025+
\code{TypeError} being raised. In order to set a method attribute,
1026+
you need to explicitly set it on the underlying function object:
10181027

10191028
\begin{verbatim}
10201029
class C:
10211030
def method(self):
10221031
pass
10231032
10241033
c = C()
1025-
d = C()
1026-
c.method.whoami = 'my name is c'
1027-
d.method.whoami = 'my name is d'
1034+
c.method.im_func.whoami = 'my name is c'
10281035
\end{verbatim}
10291036

1030-
If bound method attribute setting was allowed, \code{c.method.whoami}
1031-
would return ``my name is d''.
1032-
10331037
See the \citetitle[../ref/ref.html]{Python Reference Manual} for more
10341038
information.
10351039

0 commit comments

Comments
 (0)