Beginning Question about Python functions, parameters...
Lie Ryan
lie.1296 at gmail.com
Wed Nov 25 10:08:48 EST 2009
astral orange wrote:
>
> As for the "class Name():" example above? Even though I haven't seen
> exactly what purpose 'self' serves
In many other programming language, self (or this, or Me) refers the the
current class instance. In some languages, you can refer to an instance
attribute without an explicit self, this, or Me; the name resolver will
search in the local namespace (method-level), instance namespace
(instance-level), class namespace (class-level), perhaps module level
namespace (file-level), and finally global (application level).
Python interpreter is simple and stupid. It doesn't have many smarts;
instead of having such a sophisticated name resolver, the compiler
passes an argument to the function, making `self` a local variable that
refers to the current instance.
Python programmers accesses instance and class namespace by explicitly
referring to `self`; the name resolver only have two places to lookup
names: local namespace (method level) and global namespace (module-level
[!] not application level in python).
This choice of design simplifies the name resolver, simplifies
method/function object design (since it does not need any code to handle
an otherwise implicit self), and completely eliminates ambiguity (to the
programmer) when having a local variable with the same name as an
instance variable. Among many other advantages.
The side-effect of this design choice is self must be explicitly
referenced to access class/instance attributes; unlike in some other
language where self/this/Me may be omitted when it doesn't clash with
other variable in local namespace.
More information about the Python-list
mailing list