1313

Consider this example:

class MyClass:
    def func(self, name):
        self.name = name

I know that self refers to the specific instance of MyClass. But why must func explicitly include self as a parameter? Why do we need to use self in the method's code? Some other languages make this implicit, or use special syntax instead.


For a language-agnostic consideration of the design decision, see What is the advantage of having this/self pointer mandatory explicit?.

To close debugging questions where OP omitted a self parameter for a method and got a TypeError, use TypeError: method() takes 1 positional argument but 2 were given instead. If OP omitted self. in the body of the method and got a NameError, consider How can I call a function within a class?.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
richzilla
  • 40,440
  • 14
  • 56
  • 86
  • 127
    You may find interesting this essay "Why explicit self has to stay" by Guido van Rossum: http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html – unutbu Apr 25 '10 at 20:35
  • 15
    See also "Why must 'self' be used explicitly in method definitions and calls": http://docs.python.org/faq/design.html#why-must-self-be-used-explicitly-in-method-definitions-and-calls – unutbu Apr 25 '10 at 20:38
  • 39
    "Which i understand, quite easily" --- Quite subjective, don't you think? What makes `@name` more intuitive than `self.name`? The latter, IMO, is more intuitive. – Santa Apr 28 '10 at 00:12
  • 3
    Although to play devils advocate its very easy to forget to add an additional argument to each method and have bizarre behavior when you forget which makes it hard for beginners. IMHO I rather be specific about unusual things like static methods then normal behavior like instance methods. – Adam Gent Apr 28 '10 at 00:29
  • 2
    @santa, it wasnt so much the @name and self.name that i didnt get, it was why every function needed an extra argument. Problem solved now though. – richzilla Apr 28 '10 at 14:44
  • Except for the Ruby comparison, this is the same ground as [ *How to avoid explicit 'self'?* ](http://stackoverflow.com/q/1984121) (Because of that difference, I wouldn't close as a dupe, but anyone interested should definitely read both sets of answers.) –  Nov 11 '10 at 10:07
  • 1
    @Piotr - I assume you disable the garbage collector? It's better to explicitly manage memory than to have some garbage collector going around implicitly freeing memory all the time. – Jason Baker Nov 22 '10 at 21:25
  • 18
    That's the key difference between a function and a class method. A function is floating free, unencumbered. A class (instance) method has to be aware of it's parent (and parent properties) so you need to pass the method a reference to the parent class (as **self**). It's just one less implicit rule that you have to internalize before understanding OOP. Other languages choose syntactic sugar over semantic simplicity, python isn't other languages. – Evan Plaice Jan 17 '12 at 06:59
  • 3
    @CatPlusPlus "explicit is better than implicit" is rule 2 of the Zen of Python; rule 1 is "beautiful is better than ugly" which argues for omitting self. – I. J. Kennedy Jun 19 '12 at 16:34
  • @I.J.Kennedy: Not really, no. Sigils or implicit scopes are way more ugly. Not that implicitness with no sigil would work, anyway, in the presence of class attributes and no static verification. – Cat Plus Plus Jun 19 '12 at 16:55
  • 2
    Well, you never 'pass', `self`. You would call the method like `getUserType()`. If you needed another parameter, yes, you would need to define the method to take another parameter. – Daniel Rosenthal Aug 16 '13 at 17:09
  • 2
    Yuck, self. Why doesn't the compiler just handle it and make self a keyword? It's not that bad since it's already in many programming languages as 'this' or something similar. In all my experience, too much of something is bad for you. Too much candy, too much water, and too many explicit calls. Explicit is only > Implicit when explicit is more handy. If we're going to make self explicit, why not make the entire language explicit and have the users write and compile it themselves? –  Sep 22 '13 at 23:37
  • See also: [TypeError: Missing 1 required positional argument: 'self'](/q/17534345/). – Karl Knechtel Sep 05 '22 at 07:08

26 Answers26

786

The reason you need to use self. is because Python does not use special syntax to refer to instance attributes. Python decided to do methods in a way that makes the instance to which the method belongs be passed automatically, but not received automatically: the first parameter of methods is the instance the method is called on. That makes methods entirely the same as functions, and leaves the actual name to use up to you (although self is the convention, and people will generally frown at you when you use something else.) self is not special to the code, it's just another object.

Python could have done something else to distinguish normal names from attributes -- special syntax like Ruby has, or requiring declarations like C++ and Java do, or perhaps something yet more different -- but it didn't. Python's all for making things explicit, making it obvious what's what, and although it doesn't do it entirely everywhere, it does do it for instance attributes. That's why assigning to an instance attribute needs to know what instance to assign to, and that's why it needs self..

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Thomas Wouters
  • 130,178
  • 23
  • 148
  • 122
  • 1
    There is the exception of using *cls* instead of *self*, for example when using the *@classmethod* decorator. – Georg Schölly Apr 25 '10 at 20:30
  • 26
    @Georg: `cls` refers to the class object, not instance object – SilentGhost Apr 25 '10 at 20:33
  • 5
    The exception is when it's not a "regular" method, or "instance method", but something else -- a classmethod or a staticmethod or just a plain function :) – Thomas Wouters Apr 25 '10 at 20:55
  • 21
    @SilentGhost: Actually, the name of the first parameter is whatever you want it to be. On class methods, the convention is to use `cls` and `self` is used conventionally for instance methods. If I wanted, I could use `self` for classmethods and `cls` for instance methods. I could also use `bob` and `fnord` if I liked. – SingleNegationElimination Nov 22 '10 at 22:13
  • 75
    I find it interesting that the community didn't choose `this` instead of `self`. Does `self` have some history that I'm not aware of in older programming languages? – Jules G.M. Dec 12 '12 at 20:46
  • 29
    @Julius The `self` came from Modula-3's conventions, see [this answer](http://stackoverflow.com/questions/13652006/why-accessing-to-class-variable-from-within-the-class-needs-self-in-python/13652256#13652256) for further details on this choice. (Disclaimer: its mine). – Bakuriu Sep 20 '13 at 19:07
  • 5
    @ThomasWouters - Is it correct to say that "self" keyword of python is EXACTLY the same as the "this" keyword of Java ? If not, what are the differences ? – Erran Morad Mar 18 '14 at 18:01
  • 12
    @Julius The `self` keyword (Smalltalk, 1980) predates the `this` keyword (from C++). See: https://stackoverflow.com/questions/1079983/why-do-pythonistas-call-the-current-reference-self-and-not-this/1080192#1080192 – Wes Turner Nov 08 '14 at 18:42
  • 3
    It would be nice if self was given to us behind the scenes like Lua and C++ (this) does. " Python's all for making things explicit, making it obvious what's what, and although it doesn't do it entirely everywhere, it does do it for instance attributes." Good thing you ended it that way because coming from other languages I was about to argue the first part of that. Using white space for meaning is NOT an explicit thing at all and it's at the core of python. I'd argue compared to other languages Python isn't very explicit at all. So why stop with explicitly declaring self is the question. – user441521 Jan 12 '16 at 18:24
  • 1
    https://docs.python.org/2/tutorial/classes.html#random-remarks _Often, the first argument of a method is called `self`. This is nothing more than a convention: the name self has absolutely no special meaning to Python._ – noobninja Aug 18 '16 at 18:11
  • 1
    I think that this statement deserves a bold: the first parameter of methods is the instance the method is called on. – ivanleoncz Mar 22 '17 at 18:59
  • Python instance methods look like C# extension methods, where the first parameter refers to the instance, regardless of the name you choose for it. In my opinion, it's ugly and unnecessary, but if I wanted a language which suited all my preferences, I should probably make my own programming language. – Alisson Reinaldo Silva Mar 28 '18 at 03:07
  • 1
    This would be explicit only if method would be call like: o = myClass(); myFunc(o, "name"); – Puck Jul 30 '18 at 08:31
  • 1
    This answer is missing a very important part on the _true_reasons for the explicit `self`, which - as explained here https://wiki.python.org/moin/FromFunctionToMethod - is that python "methods" are actually just plain functions, so the language needed a way to pass the current instance to the function. – bruno desthuilliers Feb 25 '19 at 14:22
  • While I was editing the question (to polish it as much as possible, since this is an important canonical), it wasn't completely clear to me whether the question was originally *also* wondering about the need to write `self.` in the code of the function, or *only* about the need to include a `self` parameter. (It might sound strange to suppose that one doesn't follow from the other; but I've seen many questions where OP wrote a `self` parameter but then didn't expect to need to use it). Since this answer is *specifically about* the `self.` usage, and *was accepted by OP*, I feel better now. – Karl Knechtel Sep 05 '22 at 07:06
613

Let's say you have a class ClassA which contains a method methodA defined as:

class ClassA:
    def methodA(self, arg1, arg2):
        ... # do something

and objectA is an instance of this class.

Now when objectA.methodA(arg1, arg2) is called, python internally converts it for you as:

ClassA.methodA(objectA, arg1, arg2)

The self variable refers to the object itself.

mousetail
  • 7,009
  • 4
  • 25
  • 45
Arjun Sreedharan
  • 11,003
  • 2
  • 26
  • 34
  • 146
    I read all the other answers and sort of understood, I read this one and then it all made sense. – Seth Oct 08 '14 at 02:37
  • 6
    Why not keep those guts inside, though, like Ruby does? – Cees Timmerman Sep 21 '17 at 18:15
  • But in __init__(self) method, it accepts self, then even without creating the object, how does it refer to itself? – saurav Jan 28 '18 at 10:10
  • 1
    This doesn't answer the question though. The OP was asking about why `self` has to be explicitly defined. – Rain Jul 13 '21 at 08:05
  • Why then a new function is generated for every instance of `classA`? It seems from this internal conversion that is more appropriate to say that `methodA` is method of the class and not of the instance. – ado sar Aug 01 '22 at 23:12
  • 1
    @saurav `__init__` doesn't create the object; it *initializes* the object by determining its initial state. When you call `MyClass()`, there are several steps behind the scenes. In normal cases: `MyClass.__call__` is looked up and found in `type` (the usual metaclass for classes); that is called, which will call `MyClass.__new__` and **then** pass the result as `self` to `MyClass.__init__`. Meanwhile, `MyClass.__new__` usually defaults to `object.__new__`, which creates a new object of the specified class (i.e., sets its `__class__` and gives it an empty `__dict__` to hold attributes). – Karl Knechtel Sep 05 '22 at 07:18
440

Let’s take a simple vector class:

class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

We want to have a method which calculates the length. What would it look like if we wanted to define it inside the class?

    def length(self):
        return math.sqrt(self.x ** 2 + self.y ** 2)

What should it look like when we were to define it as a global method/function?

def length_global(vector):
    return math.sqrt(vector.x ** 2 + vector.y ** 2)

So the whole structure stays the same. How can me make use of this? If we assume for a moment that we hadn’t written a length method for our Vector class, we could do this:

Vector.length_new = length_global
v = Vector(3, 4)
print(v.length_new()) # 5.0

This works because the first parameter of length_global, can be re-used as the self parameter in length_new. This would not be possible without an explicit self.


Another way of understanding the need for the explicit self is to see where Python adds some syntactical sugar. When you keep in mind, that basically, a call like

v_instance.length()

is internally transformed to

Vector.length(v_instance)

it is easy to see where the self fits in. You don't actually write instance methods in Python; what you write is class methods which must take an instance as a first parameter. And therefore, you’ll have to place the instance parameter somewhere explicitly.

empty
  • 5,194
  • 3
  • 32
  • 58
Debilski
  • 66,976
  • 12
  • 110
  • 133
  • 4
    Vector.length_new = length_global... I actually started to use syntax like this in my class declarations. Whenever I only want to inherit some of the methods from another class, I just explicitly copy the reference to the methods. – Jeeyoung Kim Nov 22 '10 at 21:37
  • 2
    would it be fair to say that python's "instance method" is simply a syntactic sugar of static global methods (as in Java or C++) with an instance object passed in to package multiple attributes? --- well this is kind of half-true since in polymorphism, the more important purpose of "this" (as in java) or "self" is to give u the correct implementation of methods. Python does have this. so calling myobj.someMethod() is equal to TheClassOfMyObj.someMethod(myobj) in python. note that the "TheClassOfMyObj" is automatically figured out by python from "self", otherwise u'd have to find that out. – teddy teddy Sep 07 '12 at 19:43
  • 4
    Infact, not only are instance methods just class methods, but methods are just functions which are members of a class, as the `Vector.length_new = length_global` shows. – RussW Sep 06 '13 at 09:46
  • 1
    "This works, because the first parameter of length_global, can be re-used as the self parameter in length_new. This would not be possible without an explicit self." - it would work just the same. it would be re-used for the implicit self... the second example is a circular reasoning - you have to explicitly place self there, because python needs the explicit self. – Karoly Horvath Mar 15 '14 at 16:16
  • 1
    @KarolyHorvath: Sure, it would also be possible to have a language with a model where internally defined methods do not need an explicit self but externally defined methods do. But I’d say there is some consistency in requiring the explicit self in both cases, which makes it a legitimate reason to do it this way. Other languages may choose different approaches. – Debilski Mar 16 '14 at 14:52
  • So, with Ruby, would refactoring between a function and a method require searching for each of the `@variables` and removing the `@` sign? (Great answer, thanks!) – Wes Turner Nov 08 '14 at 18:50
  • I think that even more technically, `v_instance.length()` is transformed to `Vector.length.__get__(v_instance, Vector)()`, but that might make the waters a little more muddy than we want them ;-) – mgilson Apr 30 '16 at 02:46
  • @mgilson: Or even something like `type(v_instance)` instead of `Vector` before that. – Debilski Apr 30 '16 at 09:38
  • as someone who is learning python after ruby, the last paragraph greatly summarizes the distinction of self – random-forest-cat Feb 14 '17 at 17:43
  • "You don't actually write instance methods in Python; what you write is class methods which (must) take an instance as a first parameter. And therefore, you’ll have to place the instance parameter somewhere explicitly." *This* explained it more clearly than the text directly above. – Sergio Mar 17 '17 at 19:53
  • The last paragraph is very good. This should be the top answer. – kiwicomb123 Jun 12 '18 at 20:32
250

When objects are instantiated, the object itself is passed into the self parameter.

enter image description here

Because of this, the object’s data is bound to the object. Below is an example of how one might like to visualize what each object’s data might look. Notice how self is replaced with the object's name. I'm not saying this example diagram below is wholly accurate, but it will hopefully help one visualize the use of self.

enter image description here

The Object is passed into the self parameter so that the object can keep hold of its own data.

Although this may not be wholly accurate, think of the process of instantiating (creating and assigning internal values) an object like this: When an object is made, the object uses the class as a template for its (the object's) own data and methods. Without passing the object's own variable name into the self parameter, the attributes and methods in the class would remain a general template and would not be referenced to (belong to) the object. So, by passing the object's name into the self parameter, it means that if 100 objects are instantiated from the one class, each of the 100 objects can keep track of its (each object's) own data and methods.

Summary: Classes are general (not ultra-specific) templates that a newly created object can pass its own specific data into (without necessarily affecting the rest of the objects that could be created from the same class), allowing for less copy-pasted code that serves the purpose of creating many objects that have the same patterns. self is for specifying that a specific object's data should be used instead of some other data.

See the illustration below:

enter image description here

Stev
  • 65
  • 1
  • 7
sw123456
  • 3,339
  • 1
  • 24
  • 42
  • 1
    Hey there, when accessing Bob's attributes for example by "bob.name()", you actually accesing bob().self.name so to speak from the '__init__' right? – udarH3 Aug 10 '15 at 08:31
  • 7
    When you write bob.name() in the above comment, you are implying that bob has a method called name() due to the fact that you added brackets after name. In this example however there is no such method. 'bob.name' (which has no parenthesis) is directly accessing the attribute called name from the init (constructor) method. When bob's speak method is called it is the method which accesses the name attribute and returns it in a print statement. Hope this helps. – sw123456 Aug 10 '15 at 08:48
  • Yeah without paranthesis i wanted to write sry. So the value of name you actually get it and not of self.name because as far as i know self.name and name are 2 different variable. Thanks – udarH3 Aug 10 '15 at 09:07
  • 4
    No, you get the value of self.name, which for the bob object is actually bob.name, because the object's name is passed into the self parameter when it is created (instantiated). Again, hope this helps. Feel free to upvote main post if it has. – sw123456 Aug 10 '15 at 09:18
  • 4
    Name is assigned to self.name at instantiation. After an object is created, all variables that belong to the object are those prefixed with 'self.' Remember that self is replaced with the object's name when it is created from the class. – sw123456 Aug 10 '15 at 09:23
  • Very clear explanation. But, how to validate its correctness? – fishiwhj Apr 19 '16 at 13:03
  • 9
    This is how you explain stuff ! nice job :) – penta Nov 05 '17 at 09:44
  • 1
    Thanks makes more sense through your explanation. – Learning_Learning Aug 09 '21 at 12:55
  • What happens if I don't use self but just age, sex, name...? – skan Sep 21 '22 at 19:24
87

I like this example:

class A: 
    foo = []

a, b = A(), A()
a.foo.append(5)

b.foo  # [5]
class A: 
    def __init__(self): 
        self.foo = []

a, b = A(), A()
a.foo.append(5)

b.foo  # []
InSync
  • 4,851
  • 4
  • 8
  • 30
kame
  • 20,848
  • 33
  • 104
  • 159
  • 21
    so vars without self is simply static vars of the class, like in java – teddy teddy Sep 07 '12 at 19:45
  • 7
    teddy teddy, you aren't entirely correct. The behavior (static or non-static like) depends not only on `self` but also on the variable type. Try to do the first example with simple integer instead of list. The result would be quite different. – Konstantin Mar 27 '14 at 19:18
  • 2
    Actually, my question with this is why are you allowed to say `a.foo` in the first example, rather than `A.foo`? Clearly `foo` belongs to the class... – Resigned June 2023 Aug 06 '14 at 18:29
  • You can call static members from instances of the object in most languages. Why is that surprising? – Paarth Oct 29 '14 at 00:25
  • 2
    @RadonRosborough Because in the first example, `a` and `b` are both labels (or pointers) for `A()` (the class). `a.foo` references the `A().foo` class method. In the second example, though, `a` becomes a reference to an *instance* of `A()`, as does `b`. Now that they are instances instead of the class object itself, *self* allows the `foo` method to operate on the instances. – LegendaryDude Jul 12 '17 at 17:07
  • @LegendaryDude This is not entirely true, in *both* cases, `a` and `b` are *references to instances* of `A()`, however, in the second case, `a.foo` and `b.foo` refer to a reference inside *themselves*, whereas in the first case, `a.foo` and `b.foo` refer to a reference inside the *class*. The reason you can access references inside the *class* is for simplicity (as is so often the case in Python): Imagine a function `def bar(self): return self.foo;`. Since we can reference class members, `f = a.bar; f(a);` will do the exact same as `f = A.bar; f(a)`, and `f` will be the same in both cases. – yyny Dec 08 '20 at 11:59
46

I will demonstrate with code that does not use classes:

def state_init(state):
    state['field'] = 'init'

def state_add(state, x):
    state['field'] += x

def state_mult(state, x):
    state['field'] *= x

def state_getField(state):
    return state['field']

myself = {}
state_init(myself)
state_add(myself, 'added')
state_mult(myself, 2)

print( state_getField(myself) )
#--> 'initaddedinitadded'

Classes are just a way to avoid passing in this "state" thing all the time (and other nice things like initializing, class composition, the rarely-needed metaclasses, and supporting custom methods to override operators).

Now let's demonstrate the above code using the built-in python class machinery, to show how it's basically the same thing.

class State(object):
    def __init__(self):
        self.field = 'init'
    def add(self, x):
        self.field += x
    def mult(self, x):
        self.field *= x

s = State()
s.add('added')    # self is implicitly passed in
s.mult(2)         # self is implicitly passed in
print( s.field )

[migrated my answer from duplicate closed question]

ninjagecko
  • 88,546
  • 24
  • 137
  • 145
23

The following excerpts are from the Python documentation about self:

As in Modula-3, there are no shorthands [in Python] for referencing the object’s members from its methods: the method function is declared with an explicit first argument representing the object, which is provided implicitly by the call.

Often, the first argument of a method is called self. This is nothing more than a convention: the name self has absolutely no special meaning to Python. Note, however, that by not following the convention your code may be less readable to other Python programmers, and it is also conceivable that a class browser program might be written that relies upon such a convention.

For more information, see the Python documentation tutorial on classes.

Community
  • 1
  • 1
Matthew Rankin
  • 457,139
  • 39
  • 126
  • 163
22

As well as all the other reasons already stated, it allows for easier access to overridden methods; you can call Class.some_method(inst).

An example of where it’s useful:

class C1(object):
    def __init__(self):
         print "C1 init"

class C2(C1):
    def __init__(self): #overrides C1.__init__
        print "C2 init"
        C1.__init__(self) #but we still want C1 to init the class too
>>> C2()
"C2 init"
"C1 init"
Ry-
  • 218,210
  • 55
  • 464
  • 476
Ponkadoodle
  • 5,777
  • 5
  • 38
  • 62
18

Its use is similar to the use of this keyword in Java, i.e. to give a reference to the current object.

ChickenFeet
  • 2,653
  • 22
  • 26
Gaurav Nishant
  • 181
  • 1
  • 2
14

Python is not a language built for Object Oriented Programming, unlike Java or C++.

First off, methods belong to either an entire class (static method) or an object (instance) of the class (object method).

When calling a static method in Python, one simply writes a method with regular arguments inside it.

class Animal():
    def staticMethod():
        print "This is a static method"

However, an object (i.e., instance) method, which requires you to make an object (i.e. instance, an Animal in this case), needs the self argument.

class Animal():
    def objectMethod(self):
        print "This is an object method which needs an instance of a class"

The self method is also used to refer to a variable field within the class.

class Animal():
    #animalName made in constructor
    def Animal(self):
        self.animalName = "";

    def getAnimalName(self):
        return self.animalName

In this case, self is referring to the animalName variable of the entire class. REMEMBER: If you have a new variable created within a method (called a local variable), self will not work. That variable exists only while that method is running. For defining fields (the variables of the entire class), you have to define them OUTSIDE the class methods.

If you don't understand a single word of what I am saying, then Google "Object Oriented Programming." Once you understand this, you won't even need to ask that question :).

Stev
  • 65
  • 1
  • 7
rassa45
  • 3,482
  • 1
  • 29
  • 43
  • +1 because of the distinction between `staticMethod()` and `objectMethod(self)`. I would like to add that in order to invoke the first, you would say `Animal.staticMethod()`, while `objectMethod()` needs an instance: `a = Animal(); a.objectMethod()` – András Aszódi Jul 24 '15 at 09:37
  • What you are saying isn't 100% true. That's just a convention. You can still call the static method from an object created. You just won't be able to use any class members because you didn't declare a self. I can even call Animal.objectMethod(animalObj) to call the non static. Basically this means a static method is only a method that doesn't use member variables. There shouldn't be any need to declare self. It's a silly language requirement I think. Languages like Lua and C++ give you obj variables behind the scenes. – user441521 Jan 12 '16 at 18:20
  • 3
    You made a useless animalName string declaration and crashing animalName method. – Cees Timmerman Sep 21 '17 at 18:25
  • To @user441521, python is meant for scripting not oop , it does not excel in oop standards. To timmerman, this was written for educational purpose, its a minor error, only those who simply copy paste without understanding, which SO finds unethical, will have problems with the answer. – rassa45 Sep 21 '17 at 18:29
  • 6
    @ytpillai Irrelevant. Confusing and incorrect code should not be presented as an answer. – Cees Timmerman Sep 21 '17 at 18:34
  • Fixed the question – rassa45 Sep 21 '17 at 18:35
  • 3
    `def getAnimalName` to not clobber the string you're trying to return, and `self` refers to the instance of the class, not any field inside of it. – Cees Timmerman Sep 21 '17 at 18:38
  • _For defining fields (the variables of the entire class), you have to define them OUTSIDE the class methods._ ... The differentiation between _class attributes_ and _instance attributes_ is very vague - you can create instance attributes just fine inside instance methods - creating class attributes also works if you prefix them witht the classes name ... `Animal.ClawDamage = 200` inside `def getAnimalName(self):` works just fine -any Animal will have that attribute – Patrick Artner Feb 18 '19 at 18:05
13

First of all, self is a conventional name, you could put anything else (being coherent) in its stead.

It refers to the object itself, so when you are using it, you are declaring that .name and .age are properties of the Student objects (note, not of the Student class) you are going to create.

class Student:
    #called each time you create a new Student instance
    def __init__(self,name,age): #special method to initialize
        self.name=name
        self.age=age

    def __str__(self): #special method called for example when you use print
        return "Student %s is %s years old" %(self.name,self.age)

    def call(self, msg): #silly example for custom method
        return ("Hey, %s! "+msg) %self.name

#initializing two instances of the student class
bob=Student("Bob",20)
alice=Student("Alice",19)

#using them
print bob.name
print bob.age
print alice #this one only works if you define the __str__ method
print alice.call("Come here!") #notice you don't put a value for self

#you can modify attributes, like when alice ages
alice.age=20
print alice

Code is here

Akash Kandpal
  • 3,126
  • 28
  • 25
11

It’s there to follow the Python zen “explicit is better than implicit”. It’s indeed a reference to your class object. In Java and PHP, for example, it's called this.

If user_type_name is a field on your model you access it by self.user_type_name.

Ry-
  • 218,210
  • 55
  • 464
  • 476
dan-klasson
  • 13,734
  • 14
  • 63
  • 101
11

self is an object reference to the object itself, therefore, they are same. Python methods are not called in the context of the object itself. self in Python may be used to deal with custom object models or something.

Ming-Tang
  • 17,410
  • 8
  • 38
  • 76
8

Take a look at the following example, which clearly explains the purpose of self

class Restaurant(object):  
    bankrupt = False

    def open_branch(self):
        if not self.bankrupt:
           print("branch opened")

#create instance1
>>> x = Restaurant()
>>> x.bankrupt
False

#create instance2
>>> y = Restaurant()
>>> y.bankrupt = True   
>>> y.bankrupt
True

>>> x.bankrupt
False  

self is used/needed to distinguish between instances.

Source: self variable in python explained - Pythontips

kmario23
  • 57,311
  • 13
  • 161
  • 150
  • 1
    Yes, I think we know why self is used, but the question is why does the language make you explicitly declare it. Many other languages don't require this and a language which prides itself on being brief, you'd think they would just give you the variable behind the scenes to use like Lua or C++ (this) does. – user441521 Jan 12 '16 at 18:13
  • 3
    @kmario23 You're response was from here: https://pythontips.com/2013/08/07/the-self-variable-in-python-explained/ Please always acknowledge original authors when posting answers as your own. – geekidharsh Apr 13 '18 at 18:12
8

I'm surprised nobody has brought up Lua. Lua also uses the 'self' variable however it can be omitted but still used. C++ does the same with 'this'. I don't see any reason to have to declare 'self' in each function but you should still be able to use it just like you can with lua and C++. For a language that prides itself on being brief it's odd that it requires you to declare the self variable.

user441521
  • 6,942
  • 23
  • 88
  • 160
8

The use of the argument, conventionally called self isn't as hard to understand, as is why is it necessary? Or as to why explicitly mention it? That, I suppose, is a bigger question for most users who look up this question, or if it is not, they will certainly have the same question as they move forward learning python. I recommend them to read these couple of blogs:

1: Use of self explained

Note that it is not a keyword.

The first argument of every class method, including init, is always a reference to the current instance of the class. By convention, this argument is always named self. In the init method, self refers to the newly created object; in other class methods, it refers to the instance whose method was called. For example the below code is the same as the above code.

2: Why do we have it this way and why can we not eliminate it as an argument, like Java, and have a keyword instead

Another thing I would like to add is, an optional self argument allows me to declare static methods inside a class, by not writing self.

Code examples:

class MyClass():
    def staticMethod():
        print "This is a static method"

    def objectMethod(self):
        print "This is an object method which needs an instance of a class, and that is what self refers to"

PS:This works only in Python 3.x.

In previous versions, you have to explicitly add @staticmethod decorator, otherwise self argument is obligatory.

Bugs Buggy
  • 1,514
  • 19
  • 39
5

Is because by the way python is designed the alternatives would hardly work. Python is designed to allow methods or functions to be defined in a context where both implicit this (a-la Java/C++) or explicit @ (a-la ruby) wouldn't work. Let's have an example with the explicit approach with python conventions:

def fubar(x):
    self.x = x

class C:
    frob = fubar

Now the fubar function wouldn't work since it would assume that self is a global variable (and in frob as well). The alternative would be to execute method's with a replaced global scope (where self is the object).

The implicit approach would be

def fubar(x)
    myX = x

class C:
    frob = fubar

This would mean that myX would be interpreted as a local variable in fubar (and in frob as well). The alternative here would be to execute methods with a replaced local scope which is retained between calls, but that would remove the posibility of method local variables.

However the current situation works out well:

 def fubar(self, x)
     self.x = x

 class C:
     frob = fubar

here when called as a method frob will receive the object on which it's called via the self parameter, and fubar can still be called with an object as parameter and work the same (it is the same as C.frob I think).

skyking
  • 13,817
  • 1
  • 35
  • 57
3

In the __init__ method, self refers to the newly created object; in other class methods, it refers to the instance whose method was called.

self, as a name, is just a convention, call it as you want ! but when using it, for example to delete the object, you have to use the same name: __del__(var), where var was used in the __init__(var,[...])

You should take a look at cls too, to have the bigger picture. This post could be helpful.

Community
  • 1
  • 1
Oussama L.
  • 1,842
  • 6
  • 25
  • 31
3

self is acting as like current object name or instance of class .

# Self explanation.


 class classname(object):

    def __init__(self,name):

        self.name=name
        # Self is acting as a replacement of object name.
        #self.name=object1.name

   def display(self):
      print("Name of the person is :",self.name)
      print("object name:",object1.name)


 object1=classname("Bucky")
 object2=classname("ford")

 object1.display()
 object2.display()

###### Output 
Name of the person is : Bucky
object name: Bucky
Name of the person is : ford
object name: Bucky
sameer_nubia
  • 721
  • 8
  • 8
2

"self" keyword holds the reference of class and it is upto you if you want to use it or not but if you notice, whenever you create a new method in python, python automatically write self keyword for you. If you do some R&D, you will notice that if you create say two methods in a class and try to call one inside another, it does not recognize method unless you add self (reference of class).

class testA:
def __init__(self):
    print('ads')
def m1(self):
    print('method 1')
    self.m2()
def m2(self):
    print('method 2')

Below code throws unresolvable reference error.

class testA:
def __init__(self):
    print('ads')
def m1(self):
    print('method 1')
    m2()  #throws unresolvable reference error as class does not know if m2 exist in class scope
def m2(self):
    print('method 2')

Now let see below example

class testA:
def __init__(self):
    print('ads')
def m1(self):
    print('method 1')
def m2():
    print('method 2')

Now when you create object of class testA, you can call method m1() using class object like this as method m1() has included self keyword

obj = testA()
obj.m1()

But if you want to call method m2(), because is has no self reference so you can call m2() directly using class name like below

testA.m2()

But keep in practice to live with self keyword as there are other benefits too of it like creating global variable inside and so on.

Rahul Jha
  • 874
  • 1
  • 11
  • 28
1

self is inevitable.

There was just a question should self be implicit or explicit. Guido van Rossum resolved this question saying self has to stay.

So where the self live?

If we would just stick to functional programming we would not need self. Once we enter the Python OOP we find self there.

Here is the typical use case class C with the method m1

class C:
    def m1(self, arg):
        print(self, ' inside')
        pass

ci =C()
print(ci, ' outside')
ci.m1(None)
print(hex(id(ci))) # hex memory address

This program will output:

<__main__.C object at 0x000002B9D79C6CC0>  outside
<__main__.C object at 0x000002B9D79C6CC0>  inside
0x2b9d79c6cc0

So self holds the memory address of the class instance. The purpose of self would be to hold the reference for instance methods and for us to have explicit access to that reference.


Note there are three different types of class methods:

  • static methods (read: functions),
  • class methods,
  • instance methods (mentioned).
prosti
  • 42,291
  • 14
  • 186
  • 151
1

The word 'self' refers to instance of a class

class foo:
      def __init__(self, num1, num2):
             self.n1 = num1 #now in this it will make the perimeter num1 and num2 access across the whole class
             self.n2 = num2
      def add(self):
             return self.n1 + self.n2 # if we had not written self then if would throw an error that n1 and n2 is not defined and we have to include self in the function's perimeter to access it's variables
random_hooman
  • 1,660
  • 7
  • 23
0

it's an explicit reference to the class instance object.

SilentGhost
  • 307,395
  • 66
  • 306
  • 293
  • 24
    I don't think this helps richzilla to understand the reason behind it. – Georg Schölly Apr 25 '10 at 20:30
  • 2
    @SilentGhost: you have nailed it. I am impressed. if I understand it correctly: I do create an object as an instance of the defined class and the self parameter refers to that object? I understand self refers in implicit way to the class itself but it would be great if you explain your answer a bit more. – Dariusz Krynicki Oct 09 '17 at 14:51
0

from the docs,

the special thing about methods is that the instance object is passed as the first argument of the function. In our example, the call x.f() is exactly equivalent to MyClass.f(x). In general, calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method’s instance object before the first argument.

preceding this the related snippet,

class MyClass:
    """A simple example class"""
    i = 12345

    def f(self):
        return 'hello world'

x = MyClass()

laxman
  • 1,781
  • 4
  • 14
  • 32
0

I would say for Python at least, the self parameter can be thought of as a placeholder. Take a look at this:

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

p1 = Person("John", 36)

print(p1.name)
print(p1.age)

Self in this case and a lot of others was used as a method to say store the name value. However, after that, we use the p1 to assign it to the class we're using. Then when we print it we use the same p1 keyword.

Hope this helps for Python!

Rishi
  • 41
  • 4
0

my little 2 cents

In this class Person, we defined out init method with the self and interesting thing to notice here is the memory location of both the self and instance variable p is same <__main__.Person object at 0x106a78fd0>

class Person:

    def __init__(self, name, age):
        self.name = name 
        self.age = age 

    def say_hi(self):
        print("the self is at:", self)
        print((f"hey there, my name is {self.name} and I am {self.age} years old"))

    def say_bye(self):
        print("the self is at:", self)
        print(f"good to see you {self.name}")

p = Person("john", 78)
print("the p is at",p)
p.say_hi()  
p.say_bye() 

so as explained in above, both self and instance variable are same object.

saran
  • 356
  • 1
  • 3
  • 14