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!
From The History of Python: Adding Support for User-defined Classes:
So, stated by the BDFL himself, the only real reason he decided to use explicit self over implicit self is that:
Edit: There is also an answer in the Python FAQ.