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.

fluffy
  • 5,212
  • 2
  • 37
  • 67
Darren Young
  • 10,972
  • 36
  • 91
  • 150

4 Answers4

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.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • 42
    +1 Because in Python `self` is just a variable name that represents the instance object! – jathanism May 16 '11 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 '17 at 02: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](http://neopythonic.blogspot.de/2008/10/why-explicit-self-has-to-stay.html) for further reasons. It's also not true that everyone else uses implicit access to `self`, nor is what everyone else does always better. – Sven Marnach Mar 10 '17 at 10:08
  • oh so I don't understand... can i do `def f(): self.member = 42` ? – Toskan Mar 10 '17 at 18:32
  • i read the article and I don't really see the added value in exchange for having to hand in self on each function call. You could make it, thanks to type hinting, optional. Say `def: f(PythonSelf self)`, not hand in PythonSelf -> implicit. And thus not lose the advantages of it while not annoying everyone else with its existence. The main point I took from the article is backwards compatibility. And that is a fair enough point, looking at the python 2 vs 3 drama. So clearly an old relic to me. – Toskan Mar 10 '17 at 18:47
  • 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. – Sven Marnach Mar 12 '17 at 13:52
  • @Toskan: `self` is already acccess implicitly. You only explicitly declare `self` once, in the method signatures, `self` passing on method call is done implicitly, not sure what your issue is? In your example, `def f(self): self.member = 42`. Then when you actually call `f()` you don't pass in `self` again: `retval = f() # self.member is now 42`. This makes sense because how else does `f` access instance namespace `self` vs. class namespace? – cowbert Aug 03 '17 at 14:41
  • @cowbert ok, so what is the use of always defining self in the function creation, when you cannot use it when you call `f`? e.g. I cannot seem to be able to do `f(differentinstanceofanobject)` so what is it worth if you cannot do so? – Toskan Aug 04 '17 at 16:54
  • @Toskan huh? if `f` is a regular method of `class C` and `c = C()`, then you'd call `f` on `c` using `c.f()`, which always passes `c` as the first arg of `f`. This is what makes it implicit. This is also why `f`'s signature requires at least 1 arg, which by convention is `self`. This ensures the code inside `f` has access to `c`'s namespace. If you then have `differentinstanceofanobject = C()`, and `def f(self, obj):` then you can call `c.f(differentinstanceofanobject)` and `c.f` will have access to both `c` and `differentinstanceofanobject`. – cowbert Aug 04 '17 at 19:23
  • why explicitly define `self` as argument when you cannot do `d = D()` `c.f(d)`. It must be an old relic. No other programming language has that quirk. Seems pretty useless to me. – Toskan Aug 04 '17 at 23:43
  • @Toskan You are clearly trolling here. "No other programming language has that quirk." This is untrue, it's actually pretty common, e.g. in Perl 5 and Dylan. Even more recent languages like Rust decided to pass self explicitly. People prefer it that way, for reasons given in Nick's answer below and Guido's blog post. – Sven Marnach Aug 07 '17 at 11:10
  • @SvenMarnach guidos blog post... yes I read it. Basically he gives some examples and then says "well i guess those are solvable with implicit self too" yes I agree with him, so 0 points pro explicit `self` so far. Then he mentions decorators and fails to give a solid example. He says "we cannot know if it is static or not" well at some point you will know if it is static or not. I'm not saying it's trivial to solve. But it is clearly solvable. And only because some other programming languages were cutting corners, that's really not a good enough excuse to me. – Toskan Aug 08 '17 at 23:15
  • actually the most convincing argument guido brought forward was the "method poking". Imho you could poke as well, say, a global function with `def f() this.xyz()` but it would be odd. Now if you argue "handing in self makes it easier to bring forward python as whole" well, I would be ok with that. I think that is what ncoghlan tried to say. It's just easier. – Toskan Aug 08 '17 at 23:21
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.

ncoghlan
  • 40,168
  • 10
  • 71
  • 80
  • 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 03 '11 at 02: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.

Asclepius
  • 57,944
  • 17
  • 167
  • 143
Xiao Hanyu
  • 1,402
  • 16
  • 11
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.

The Sun
  • 51
  • 3