60

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.method() or self.intvalue, for example?

I just want to check that there isn't a less verbose way that I have not encountered yet.

3

4 Answers 4

125

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 self.

13
  • 42
    +1 Because in Python self is just a variable name that represents the instance object!
    – jathanism
    May 16, 2011 at 15:29
  • 2
    sorry for the hate, but what is that? medieval times? you really hand 'self' on each function call? what is the reason python is not able to get out of the paper bag like everyone else and provide access to self implicitly?
    – Toskan
    Mar 10, 2017 at 2:42
  • 1
    @Toskan No, you don't have pass self explicitly on every function call. It is passed implicitly; you just have to accept it explicitly on the method. I for one prefer having to use self explicitly since it keeps scoping cleaner. See also Nick's answer below and Guido's blog for further reasons. It's also not true that everyone else uses implicit access to self, nor is what everyone else does always better. Mar 10, 2017 at 10:08
  • oh so I don't understand... can i do def f(): self.member = 42 ?
    – Toskan
    Mar 10, 2017 at 18:32
  • 1
    @Toskan Well, there are many points raised in my comment, in Nick's answer below and in Guido's blog post. I won't repeat them here. You don't have to agree with them, but please accept that other people genuinely prefer it the way it is, and have reasons other than backwards compatibility. Mar 12, 2017 at 13:52
55

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 self.

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

1
  • 6
    To expand on that "largely irrelevant" point in regards to class scopes, the one exception is the __class__ magic variable in Python 3.x (also implicitly referenced when the builtin super() is used in a method). When the compiler sees that magic variable name, it creates an automatic closure reference that it later fills in with the fully constructed class. This works only for methods that are actually defined inside a class scope - monkey-patched methods must name the class explicitly (as all functions have to do in 2.x). See PEP 3135 for details.
    – ncoghlan
    Aug 3, 2011 at 2:50
9

First, Python's self is not a keyword, it's a coding convention, the same as Python's cls.

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 self and cls, and why they are necessary.

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

0

[Images of the Exampleenter image description here1[Simple Example] [2]** What is Self **

  1. Within the python class is refer to current object, some variable must be required which is nothing but self.

2)Self is reference variable always pointing to current object.

3)The first argument to the constructor and instance method is always self.

4)At the time of calling constructor or instance method, we are not required to pass any value to Self variable.Internally PVM(Python Virtual Machine) is responsible to provide value.

5)The Main purpose of self variable within the class is to declare instance variable, and to access the value of instance variable.

##6) Self in not a Keyword and insted of 'Self' we can use any name like Dog,Cat.But recommended to use Self.

##7) We can not use self from outside of the class.

1
  • Please dont use screenshot of the code and past the code (as well as the console output) as text Jul 27, 2022 at 3:59

Not the answer you're looking for? Browse other questions tagged or ask your own question.