I am new to Python (usually work on C#), started using it over the last couple of days.
Within a class, do you need to prefix any call to that classes data members and methods? So, if I am calling a method or obtaining a value from that class, from within that class, I need to use
self.intvalue, for example?
I just want to check that there isn’t a less verbose way that I have not encountered yet.
There is no less verbose way. Always use
self.x to access the instance attribute
x. Note that unlike
this in C++,
self is not a keyword, though. You could give the first parameter of your method any name you want, but you are strongly advised to stick to the convention of calling it
I’ll supplement Sven’s (accurate) response with an answer to the natural follow-up question (i.e. Why is
self explicit rather than implicit?).
Python works this way as it operates on the idea of lexical scoping: bare name references will always refer to a local variable within the current function definition, a local variable of a containing function definition, a global variable of the module, or a builtin. (The scoping is lexical as when you follow the parse tree down during symbol analysis, you only need to remember the names seen in the function definitions on the path down to the current function – anything else can be handled as “not seen, therefore global or builtin”. It’s also worth explicitly noting that the scoping rules relate to nesting of function definitions rather than calls).
Methods are not given any particular special treatment in that regard – class statements are largely irrelevant to the lexical scoping rules, since there isn’t the same sharp function vs method distinction that exists in some languages (Instead, methods are dynamically created from functions when the relevant attributes are retrieved from objects).
This allows a function to be added to a class after it has already been defined and be indistinguishable from those methods that were defined within the body of the class statement (a process known as “monkeypatching”).
Since object namespaces are separate from the lexical scoping rules, it is necessary to provide some other way to reference those attributes. This is the task handled by the explicit
Note that for complex algorithms, it is not uncommon to cache references to member variables as local variables within the method.
self is not a keyword, it’s a coding convention, the same as Python’s
Guido has written a really detailed and valuable article about the origin of Python’s support for class, and in that article, Guido explains why use
cls, and why they are necessary.