Python 'self' keyword

I'm new to Python (usually working in C #), started using it in the last couple of days.

Inside a class, do you need a prefix for any data call and class data methods? So, if I call a method or get a value from this class, from this class do I need to use self.method () or self.intvalue, for example?

I just want to check that there is not yet a more detailed way that I have not yet encountered.

+52
python
May 16 '11 at 15:25
source share
3 answers

There is no less detailed way. Always use self.x to access the instance attribute x . Note that unlike this in C ++, self not a keyword. You can give the first parameter of your method whatever name you want, but you are strongly advised to stick to the convention of calling it self .

+111
May 16 '11 at 03:27
source share

I will add a Sven (exact) answer with an answer to the natural question about the next steps (i.e. why is self explicit and not implicit?).

Python works this way because it works on the idea of ​​lexical scope: references to the names you search for will always refer to a local variable in the current function definition, a local variable containing the function definition, a global module variable, or inline. (The scope of the vocabulary is, as when you follow the parse tree during character analysis, you only need to remember the names visible in the function definitions on the way to the current function - everything that can be processed as “not visible”, therefore global or built-in ". It’s also worth noting directly that the rules for defining coverage apply to nesting function definitions, not calls."

The methods are not given special treatment in this regard - class statements are largely irrelevant to the lexical rules of definition, since in some languages ​​there is not such an acute function as the difference in methods, but there is a method of dynamic creation from functions when the corresponding attributes are extracted from objects).

This allows you to add a function to the class after it is already defined and is indistinguishable from those methods that were defined inside the body of the class operator (a process known as "monkeypatching").

Since the object namespaces are separated from the lexical rules for determining the scope, it is necessary to specify a different way of referring to these attributes. This is a task handled by an explicit self .

Note that for complex algorithms, it is not uncommon to cache references to member variables as local variables within a method.

+50
May 16 '11 at 15:54
source share

Firstly, Python self not a keyword, it is a coding convention, the same as Python cls .

Guido wrote a very detailed and valuable article on the origin of Python support for the class, and in this article Guido explains why to use self and cls , and why they are needed.

See http://python-history.blogspot.com/2009/02/adding-support-for-user-defined-classes.html .

+7
Jul 01 '13 at 7:03 on
source share



All Articles