Gill Bates Gill Bates - 5 months ago 7
Python Question

Why accessing to class variable from within the class needs "self." in Python?


Possible Duplicate:

Python ‘self’ explained




I'm learning Python and I have a question, more theoretical than practical, regarding access class variables from method of this class.

For example we have:

class ExampleClass:
x = 123
def example_method(self):
print(self.x)


Why is necessarily to write exactly
self.x
, not just
x
?
x
belongs to namespace of the class, and method using it belongs to it too. What am I missing? What a rationale stands behind such style?

In C++ you can write:

class ExampleClass {
public:
int x;
void example_method()
{
x = 123;
cout << x;
};
};


And it will work!

Answer

From The History of Python: Adding Support for User-defined Classes:

Instead, I decided to give up on the idea of implicit references to instance variables. Languages like C++ let you write this->foo to explicitly reference the instance variable foo (in case there’s a separate local variable foo). Thus, I decided to make such explicit references the only way to reference instance variables. In addition, I decided that rather than making the current object ("this") a special keyword, I would simply make "this" (or its equivalent) the first named argument to a method. Instance variables would just always be referenced as attributes of that argument.

With explicit references, there is no need to have a special syntax for method definitions nor do you have to worry about complicated semantics concerning variable lookup. Instead, one simply defines a function whose first argument corresponds to the instance, which by convention is named "self." For example:

def spam(self,y):
    print self.x, y

This approach resembles something I had seen in Modula-3, which had already provided me with the syntax for import and exception handling. Modula-3 doesn’t have classes, but it lets you create record types containing fully typed function pointer members that are initialized by default to functions defined nearby, and adds syntactic sugar so that if x is such a record variable, and m is a function pointer member of that record, initialized to function f, then calling x.m(args) is equivalent to calling f(x, args). This matches the typical implementation of objects and methods, and makes it possible to equate instance variables with attributes of the first argument.

So, stated by the BDFL himself, the only real reason he decided to use explicit self over implicit self is that:

  • it is explicit
  • it is easier to implement, since the lookup must be done at runtime(and not at compile time like other languages) and having implicit self could have increased the complexity(and thus cost) of the lookups.

Edit: There is also an answer in the Python FAQ.

Comments