What is the purpose of self?
What is the purpose of the self
word in Python? I understand it refers to the specific object created from that class, but I can't see why it explicitly needs to be added to every function as a parameter. To illustrate, in Ruby I can do this:
class myClass
def myFunc(name)
@name = name
end
end
Which I understand, quite easily. However in Python I need to include self
:
class myClass:
def myFunc(self, name):
self.name = name
Can anyone talk me through this? It is not something I've come across in my (admittedly limited) experience.
python class oop self
|
show 10 more comments
What is the purpose of the self
word in Python? I understand it refers to the specific object created from that class, but I can't see why it explicitly needs to be added to every function as a parameter. To illustrate, in Ruby I can do this:
class myClass
def myFunc(name)
@name = name
end
end
Which I understand, quite easily. However in Python I need to include self
:
class myClass:
def myFunc(self, name):
self.name = name
Can anyone talk me through this? It is not something I've come across in my (admittedly limited) experience.
python class oop self
92
You may find interesting this essay "Why explicit self has to stay" by Guido van Rossum: neopythonic.blogspot.com/2008/10/…
– unutbu
Apr 25 '10 at 20:35
12
See also "Why must 'self' be used explicitly in method definitions and calls": docs.python.org/faq/…
– unutbu
Apr 25 '10 at 20:38
31
"Which i understand, quite easily" --- Quite subjective, don't you think? What makes@name
more intuitive thanself.name
? The latter, IMO, is more intuitive.
– Santa
Apr 28 '10 at 0:12
11
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 6:59
8
I don't think "explicit is better than implicit" really explains this design choice well.@foo
andself.foo
are equally explicit as no implicit resolution needs to occur (e.g. in C++, instance members can be "implicitly" accessed without "explicitly" using namespaces). The only difference is that Ruby introduces a new semantic (@), while Python does not. Whether or not a new semantic was worth the amount of verbosity avoided is purely subjective. Though, it should be noted that most modern languages choose to introduce a concept here (e.g. php's $this, JS's this).
– Jing
Jun 14 '14 at 0:09
|
show 10 more comments
What is the purpose of the self
word in Python? I understand it refers to the specific object created from that class, but I can't see why it explicitly needs to be added to every function as a parameter. To illustrate, in Ruby I can do this:
class myClass
def myFunc(name)
@name = name
end
end
Which I understand, quite easily. However in Python I need to include self
:
class myClass:
def myFunc(self, name):
self.name = name
Can anyone talk me through this? It is not something I've come across in my (admittedly limited) experience.
python class oop self
What is the purpose of the self
word in Python? I understand it refers to the specific object created from that class, but I can't see why it explicitly needs to be added to every function as a parameter. To illustrate, in Ruby I can do this:
class myClass
def myFunc(name)
@name = name
end
end
Which I understand, quite easily. However in Python I need to include self
:
class myClass:
def myFunc(self, name):
self.name = name
Can anyone talk me through this? It is not something I've come across in my (admittedly limited) experience.
python class oop self
python class oop self
edited Jan 18 '18 at 1:47
kmario23
16.4k45869
16.4k45869
asked Apr 25 '10 at 20:22
richzillarichzilla
12.9k124174
12.9k124174
92
You may find interesting this essay "Why explicit self has to stay" by Guido van Rossum: neopythonic.blogspot.com/2008/10/…
– unutbu
Apr 25 '10 at 20:35
12
See also "Why must 'self' be used explicitly in method definitions and calls": docs.python.org/faq/…
– unutbu
Apr 25 '10 at 20:38
31
"Which i understand, quite easily" --- Quite subjective, don't you think? What makes@name
more intuitive thanself.name
? The latter, IMO, is more intuitive.
– Santa
Apr 28 '10 at 0:12
11
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 6:59
8
I don't think "explicit is better than implicit" really explains this design choice well.@foo
andself.foo
are equally explicit as no implicit resolution needs to occur (e.g. in C++, instance members can be "implicitly" accessed without "explicitly" using namespaces). The only difference is that Ruby introduces a new semantic (@), while Python does not. Whether or not a new semantic was worth the amount of verbosity avoided is purely subjective. Though, it should be noted that most modern languages choose to introduce a concept here (e.g. php's $this, JS's this).
– Jing
Jun 14 '14 at 0:09
|
show 10 more comments
92
You may find interesting this essay "Why explicit self has to stay" by Guido van Rossum: neopythonic.blogspot.com/2008/10/…
– unutbu
Apr 25 '10 at 20:35
12
See also "Why must 'self' be used explicitly in method definitions and calls": docs.python.org/faq/…
– unutbu
Apr 25 '10 at 20:38
31
"Which i understand, quite easily" --- Quite subjective, don't you think? What makes@name
more intuitive thanself.name
? The latter, IMO, is more intuitive.
– Santa
Apr 28 '10 at 0:12
11
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 6:59
8
I don't think "explicit is better than implicit" really explains this design choice well.@foo
andself.foo
are equally explicit as no implicit resolution needs to occur (e.g. in C++, instance members can be "implicitly" accessed without "explicitly" using namespaces). The only difference is that Ruby introduces a new semantic (@), while Python does not. Whether or not a new semantic was worth the amount of verbosity avoided is purely subjective. Though, it should be noted that most modern languages choose to introduce a concept here (e.g. php's $this, JS's this).
– Jing
Jun 14 '14 at 0:09
92
92
You may find interesting this essay "Why explicit self has to stay" by Guido van Rossum: neopythonic.blogspot.com/2008/10/…
– unutbu
Apr 25 '10 at 20:35
You may find interesting this essay "Why explicit self has to stay" by Guido van Rossum: neopythonic.blogspot.com/2008/10/…
– unutbu
Apr 25 '10 at 20:35
12
12
See also "Why must 'self' be used explicitly in method definitions and calls": docs.python.org/faq/…
– unutbu
Apr 25 '10 at 20:38
See also "Why must 'self' be used explicitly in method definitions and calls": docs.python.org/faq/…
– unutbu
Apr 25 '10 at 20:38
31
31
"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 0:12
"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 0:12
11
11
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 6:59
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 6:59
8
8
I don't think "explicit is better than implicit" really explains this design choice well.
@foo
and self.foo
are equally explicit as no implicit resolution needs to occur (e.g. in C++, instance members can be "implicitly" accessed without "explicitly" using namespaces). The only difference is that Ruby introduces a new semantic (@), while Python does not. Whether or not a new semantic was worth the amount of verbosity avoided is purely subjective. Though, it should be noted that most modern languages choose to introduce a concept here (e.g. php's $this, JS's this).– Jing
Jun 14 '14 at 0:09
I don't think "explicit is better than implicit" really explains this design choice well.
@foo
and self.foo
are equally explicit as no implicit resolution needs to occur (e.g. in C++, instance members can be "implicitly" accessed without "explicitly" using namespaces). The only difference is that Ruby introduces a new semantic (@), while Python does not. Whether or not a new semantic was worth the amount of verbosity avoided is purely subjective. Though, it should be noted that most modern languages choose to introduce a concept here (e.g. php's $this, JS's this).– Jing
Jun 14 '14 at 0:09
|
show 10 more comments
19 Answers
19
active
oldest
votes
The reason you need to use self.
is because Python does not use the @
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.
.
19
@Georg:cls
refers to the class object, not instance object
– SilentGhost
Apr 25 '10 at 20:33
14
@SilentGhost: Actually, the name of the first parameter is whatever you want it to be. On class methods, the convention is to usecls
andself
is used conventionally for instance methods. If I wanted, I could useself
for classmethods andcls
for instance methods. I could also usebob
andfnord
if I liked.
– SingleNegationElimination
Nov 22 '10 at 22:13
61
I find it interesting that the community didn't choosethis
instead ofself
. Doesself
have some history that I'm not aware of in older programming languages?
– Julius
Dec 12 '12 at 20:46
21
@Julius Theself
came from Modula-3's conventions, see this answer for further details on this choice. (Disclaimer: its mine).
– Bakuriu
Sep 20 '13 at 19:07
7
@Julius Theself
keyword (Smalltalk, 1980) predates thethis
keyword (from C++). See: stackoverflow.com/questions/1079983/…
– Wes Turner
Nov 8 '14 at 18:42
|
show 8 more comments
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.
3
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
1
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 7 '12 at 19:43
2
Infact, not only are instance methods just class methods, but methods are just functions which are members of a class, as theVector.length_new = length_global
shows.
– RussW
Sep 6 '13 at 9: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
|
show 6 more comments
Let's say you have a class ClassA
which contains a method methodA
defined as:
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.
57
I read all the other answers and sort of understood, I read this one and then it all made sense.
– Seth
Oct 8 '14 at 2:37
5
This is called as magic answer __magic__()
– Rio
Jun 3 '15 at 19:13
1
This is already answered in the latter portion of Debilski's answer..
– SIslam
Jun 13 '15 at 15:36
1
Why not keep those guts inside, though, like Ruby does?
– Cees Timmerman
Sep 21 '17 at 18:15
5
This should have been the answer !! To the point and precise
– Spandy
Dec 12 '17 at 1:00
|
show 2 more comments
When objects are instantiated, the object itself is passed into the self parameter.
Because of this, the object’s data is bound to the object. Below is an example of how you might like to visualize what each object’s data might look. Notice how ‘self’ is replaced with the objects name. I'm not saying this example diagram below is wholly accurate but it hopefully with serve a purpose in visualizing the use of self.
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 an object like this: When an object is made it uses the class as a template for its own data and methods. Without passing it's own name into the self parameter, the attributes and methods in the class would remain as 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, they can all keep track of their own data and methods.
See the illustration below:
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 8:31
3
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 8:48
3
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 9:18
2
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 9:23
3
This is how you explain stuff ! nice job :)
– penta
Nov 5 '17 at 9:44
|
show 2 more comments
I like this example:
class A:
foo =
a, b = A(), A()
a.foo.append(5)
b.foo
ans: [5]
class A:
def __init__(self):
self.foo =
a, b = A(), A()
a.foo.append(5)
b.foo
ans:
14
so vars without self is simply static vars of the class, like in java
– teddy teddy
Sep 7 '12 at 19:45
4
teddy teddy, you aren't entirely correct. The behavior (static or non-static like) depends not only onself
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
1
Actually, my question with this is why are you allowed to saya.foo
in the first example, rather thanA.foo
? Clearlyfoo
belongs to the class...
– Radon Rosborough
Aug 6 '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 0:25
1
@RadonRosborough Because in the first example,a
andb
are both labels (or pointers) forA()
(the class).a.foo
references theA().foo
class method. In the second example, though,a
becomes a reference to an instance ofA()
, as doesb
. Now that they are instances instead of the class object itself, self allows thefoo
method to operate on the instances.
– LegendaryDude
Jul 12 '17 at 17:07
add a comment |
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]
1
I wish Python sugarcoated the handlers as well as Ruby does.
– Cees Timmerman
Sep 21 '17 at 18:18
add a comment |
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"
add a comment |
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.
add a comment |
Python is not a language built for Object Oriented Programming unlike Java or C++.
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 method, which requires you to make a variable, which is 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 variable within a method, self will not work. That variable is simply existent 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 :).
+1 because of the distinction betweenstaticMethod()
andobjectMethod(self)
. I would like to add that in order to invoke the first, you would sayAnimal.staticMethod()
, whileobjectMethod()
needs an instance:a = Animal(); a.objectMethod()
– Laryx Decidua
Jul 24 '15 at 9: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
1
The only answer that makes sense! Thank you!!!!!!!!!!!!!!!!!!!!!!!
– john
Jul 25 '17 at 1:47
2
@ytpillai Irrelevant. Confusing and incorrect code should not be presented as an answer.
– Cees Timmerman
Sep 21 '17 at 18:34
1
def getAnimalName
to not clobber the string you're trying to return, andself
refers to the instance of the class, not any field inside of it.
– Cees Timmerman
Sep 21 '17 at 18:38
|
show 3 more comments
Its use is similar to the use of this
keyword in Java, i.e. to give a reference to the current object.
class myClass: def myFunc(this, name): this.name = name
– LEM Adane
Oct 26 '12 at 12:01
add a comment |
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
.
add a comment |
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.
add a comment |
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.
add a comment |
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
add a comment |
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.
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
2
@kmario23 You're response was from here: 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
add a comment |
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).
add a comment |
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.
add a comment |
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.
add a comment |
it's an explicit reference to the class instance object.
17
I don't think this helps richzilla to understand the reason behind it.
– Georg Schölly
Apr 25 '10 at 20:30
@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.
– BlueTomato
Oct 9 '17 at 14:51
add a comment |
protected by Jon Clements♦ Apr 23 '13 at 8:26
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
19 Answers
19
active
oldest
votes
19 Answers
19
active
oldest
votes
active
oldest
votes
active
oldest
votes
The reason you need to use self.
is because Python does not use the @
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.
.
19
@Georg:cls
refers to the class object, not instance object
– SilentGhost
Apr 25 '10 at 20:33
14
@SilentGhost: Actually, the name of the first parameter is whatever you want it to be. On class methods, the convention is to usecls
andself
is used conventionally for instance methods. If I wanted, I could useself
for classmethods andcls
for instance methods. I could also usebob
andfnord
if I liked.
– SingleNegationElimination
Nov 22 '10 at 22:13
61
I find it interesting that the community didn't choosethis
instead ofself
. Doesself
have some history that I'm not aware of in older programming languages?
– Julius
Dec 12 '12 at 20:46
21
@Julius Theself
came from Modula-3's conventions, see this answer for further details on this choice. (Disclaimer: its mine).
– Bakuriu
Sep 20 '13 at 19:07
7
@Julius Theself
keyword (Smalltalk, 1980) predates thethis
keyword (from C++). See: stackoverflow.com/questions/1079983/…
– Wes Turner
Nov 8 '14 at 18:42
|
show 8 more comments
The reason you need to use self.
is because Python does not use the @
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.
.
19
@Georg:cls
refers to the class object, not instance object
– SilentGhost
Apr 25 '10 at 20:33
14
@SilentGhost: Actually, the name of the first parameter is whatever you want it to be. On class methods, the convention is to usecls
andself
is used conventionally for instance methods. If I wanted, I could useself
for classmethods andcls
for instance methods. I could also usebob
andfnord
if I liked.
– SingleNegationElimination
Nov 22 '10 at 22:13
61
I find it interesting that the community didn't choosethis
instead ofself
. Doesself
have some history that I'm not aware of in older programming languages?
– Julius
Dec 12 '12 at 20:46
21
@Julius Theself
came from Modula-3's conventions, see this answer for further details on this choice. (Disclaimer: its mine).
– Bakuriu
Sep 20 '13 at 19:07
7
@Julius Theself
keyword (Smalltalk, 1980) predates thethis
keyword (from C++). See: stackoverflow.com/questions/1079983/…
– Wes Turner
Nov 8 '14 at 18:42
|
show 8 more comments
The reason you need to use self.
is because Python does not use the @
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.
.
The reason you need to use self.
is because Python does not use the @
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.
.
edited Apr 27 '10 at 23:01
answered Apr 25 '10 at 20:25
Thomas WoutersThomas Wouters
91.3k18127108
91.3k18127108
19
@Georg:cls
refers to the class object, not instance object
– SilentGhost
Apr 25 '10 at 20:33
14
@SilentGhost: Actually, the name of the first parameter is whatever you want it to be. On class methods, the convention is to usecls
andself
is used conventionally for instance methods. If I wanted, I could useself
for classmethods andcls
for instance methods. I could also usebob
andfnord
if I liked.
– SingleNegationElimination
Nov 22 '10 at 22:13
61
I find it interesting that the community didn't choosethis
instead ofself
. Doesself
have some history that I'm not aware of in older programming languages?
– Julius
Dec 12 '12 at 20:46
21
@Julius Theself
came from Modula-3's conventions, see this answer for further details on this choice. (Disclaimer: its mine).
– Bakuriu
Sep 20 '13 at 19:07
7
@Julius Theself
keyword (Smalltalk, 1980) predates thethis
keyword (from C++). See: stackoverflow.com/questions/1079983/…
– Wes Turner
Nov 8 '14 at 18:42
|
show 8 more comments
19
@Georg:cls
refers to the class object, not instance object
– SilentGhost
Apr 25 '10 at 20:33
14
@SilentGhost: Actually, the name of the first parameter is whatever you want it to be. On class methods, the convention is to usecls
andself
is used conventionally for instance methods. If I wanted, I could useself
for classmethods andcls
for instance methods. I could also usebob
andfnord
if I liked.
– SingleNegationElimination
Nov 22 '10 at 22:13
61
I find it interesting that the community didn't choosethis
instead ofself
. Doesself
have some history that I'm not aware of in older programming languages?
– Julius
Dec 12 '12 at 20:46
21
@Julius Theself
came from Modula-3's conventions, see this answer for further details on this choice. (Disclaimer: its mine).
– Bakuriu
Sep 20 '13 at 19:07
7
@Julius Theself
keyword (Smalltalk, 1980) predates thethis
keyword (from C++). See: stackoverflow.com/questions/1079983/…
– Wes Turner
Nov 8 '14 at 18:42
19
19
@Georg:
cls
refers to the class object, not instance object– SilentGhost
Apr 25 '10 at 20:33
@Georg:
cls
refers to the class object, not instance object– SilentGhost
Apr 25 '10 at 20:33
14
14
@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
@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
61
61
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?– Julius
Dec 12 '12 at 20:46
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?– Julius
Dec 12 '12 at 20:46
21
21
@Julius The
self
came from Modula-3's conventions, see this answer for further details on this choice. (Disclaimer: its mine).– Bakuriu
Sep 20 '13 at 19:07
@Julius The
self
came from Modula-3's conventions, see this answer for further details on this choice. (Disclaimer: its mine).– Bakuriu
Sep 20 '13 at 19:07
7
7
@Julius The
self
keyword (Smalltalk, 1980) predates the this
keyword (from C++). See: stackoverflow.com/questions/1079983/…– Wes Turner
Nov 8 '14 at 18:42
@Julius The
self
keyword (Smalltalk, 1980) predates the this
keyword (from C++). See: stackoverflow.com/questions/1079983/…– Wes Turner
Nov 8 '14 at 18:42
|
show 8 more comments
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.
3
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
1
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 7 '12 at 19:43
2
Infact, not only are instance methods just class methods, but methods are just functions which are members of a class, as theVector.length_new = length_global
shows.
– RussW
Sep 6 '13 at 9: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
|
show 6 more comments
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.
3
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
1
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 7 '12 at 19:43
2
Infact, not only are instance methods just class methods, but methods are just functions which are members of a class, as theVector.length_new = length_global
shows.
– RussW
Sep 6 '13 at 9: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
|
show 6 more comments
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.
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.
edited Aug 15 '17 at 6:40
Kevin Johnsrude
1,99511640
1,99511640
answered Apr 28 '10 at 0:03
DebilskiDebilski
53.9k899128
53.9k899128
3
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
1
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 7 '12 at 19:43
2
Infact, not only are instance methods just class methods, but methods are just functions which are members of a class, as theVector.length_new = length_global
shows.
– RussW
Sep 6 '13 at 9: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
|
show 6 more comments
3
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
1
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 7 '12 at 19:43
2
Infact, not only are instance methods just class methods, but methods are just functions which are members of a class, as theVector.length_new = length_global
shows.
– RussW
Sep 6 '13 at 9: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
3
3
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
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
1
1
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 7 '12 at 19:43
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 7 '12 at 19:43
2
2
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 6 '13 at 9:46
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 6 '13 at 9:46
1
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
"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
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
@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
|
show 6 more comments
Let's say you have a class ClassA
which contains a method methodA
defined as:
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.
57
I read all the other answers and sort of understood, I read this one and then it all made sense.
– Seth
Oct 8 '14 at 2:37
5
This is called as magic answer __magic__()
– Rio
Jun 3 '15 at 19:13
1
This is already answered in the latter portion of Debilski's answer..
– SIslam
Jun 13 '15 at 15:36
1
Why not keep those guts inside, though, like Ruby does?
– Cees Timmerman
Sep 21 '17 at 18:15
5
This should have been the answer !! To the point and precise
– Spandy
Dec 12 '17 at 1:00
|
show 2 more comments
Let's say you have a class ClassA
which contains a method methodA
defined as:
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.
57
I read all the other answers and sort of understood, I read this one and then it all made sense.
– Seth
Oct 8 '14 at 2:37
5
This is called as magic answer __magic__()
– Rio
Jun 3 '15 at 19:13
1
This is already answered in the latter portion of Debilski's answer..
– SIslam
Jun 13 '15 at 15:36
1
Why not keep those guts inside, though, like Ruby does?
– Cees Timmerman
Sep 21 '17 at 18:15
5
This should have been the answer !! To the point and precise
– Spandy
Dec 12 '17 at 1:00
|
show 2 more comments
Let's say you have a class ClassA
which contains a method methodA
defined as:
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.
Let's say you have a class ClassA
which contains a method methodA
defined as:
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.
edited Jan 18 '15 at 16:10
hichris123
7,445124261
7,445124261
answered Jan 26 '14 at 17:31
Arjun SreedharanArjun Sreedharan
6,95711828
6,95711828
57
I read all the other answers and sort of understood, I read this one and then it all made sense.
– Seth
Oct 8 '14 at 2:37
5
This is called as magic answer __magic__()
– Rio
Jun 3 '15 at 19:13
1
This is already answered in the latter portion of Debilski's answer..
– SIslam
Jun 13 '15 at 15:36
1
Why not keep those guts inside, though, like Ruby does?
– Cees Timmerman
Sep 21 '17 at 18:15
5
This should have been the answer !! To the point and precise
– Spandy
Dec 12 '17 at 1:00
|
show 2 more comments
57
I read all the other answers and sort of understood, I read this one and then it all made sense.
– Seth
Oct 8 '14 at 2:37
5
This is called as magic answer __magic__()
– Rio
Jun 3 '15 at 19:13
1
This is already answered in the latter portion of Debilski's answer..
– SIslam
Jun 13 '15 at 15:36
1
Why not keep those guts inside, though, like Ruby does?
– Cees Timmerman
Sep 21 '17 at 18:15
5
This should have been the answer !! To the point and precise
– Spandy
Dec 12 '17 at 1:00
57
57
I read all the other answers and sort of understood, I read this one and then it all made sense.
– Seth
Oct 8 '14 at 2:37
I read all the other answers and sort of understood, I read this one and then it all made sense.
– Seth
Oct 8 '14 at 2:37
5
5
This is called as magic answer __magic__()
– Rio
Jun 3 '15 at 19:13
This is called as magic answer __magic__()
– Rio
Jun 3 '15 at 19:13
1
1
This is already answered in the latter portion of Debilski's answer..
– SIslam
Jun 13 '15 at 15:36
This is already answered in the latter portion of Debilski's answer..
– SIslam
Jun 13 '15 at 15:36
1
1
Why not keep those guts inside, though, like Ruby does?
– Cees Timmerman
Sep 21 '17 at 18:15
Why not keep those guts inside, though, like Ruby does?
– Cees Timmerman
Sep 21 '17 at 18:15
5
5
This should have been the answer !! To the point and precise
– Spandy
Dec 12 '17 at 1:00
This should have been the answer !! To the point and precise
– Spandy
Dec 12 '17 at 1:00
|
show 2 more comments
When objects are instantiated, the object itself is passed into the self parameter.
Because of this, the object’s data is bound to the object. Below is an example of how you might like to visualize what each object’s data might look. Notice how ‘self’ is replaced with the objects name. I'm not saying this example diagram below is wholly accurate but it hopefully with serve a purpose in visualizing the use of self.
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 an object like this: When an object is made it uses the class as a template for its own data and methods. Without passing it's own name into the self parameter, the attributes and methods in the class would remain as 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, they can all keep track of their own data and methods.
See the illustration below:
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 8:31
3
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 8:48
3
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 9:18
2
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 9:23
3
This is how you explain stuff ! nice job :)
– penta
Nov 5 '17 at 9:44
|
show 2 more comments
When objects are instantiated, the object itself is passed into the self parameter.
Because of this, the object’s data is bound to the object. Below is an example of how you might like to visualize what each object’s data might look. Notice how ‘self’ is replaced with the objects name. I'm not saying this example diagram below is wholly accurate but it hopefully with serve a purpose in visualizing the use of self.
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 an object like this: When an object is made it uses the class as a template for its own data and methods. Without passing it's own name into the self parameter, the attributes and methods in the class would remain as 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, they can all keep track of their own data and methods.
See the illustration below:
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 8:31
3
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 8:48
3
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 9:18
2
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 9:23
3
This is how you explain stuff ! nice job :)
– penta
Nov 5 '17 at 9:44
|
show 2 more comments
When objects are instantiated, the object itself is passed into the self parameter.
Because of this, the object’s data is bound to the object. Below is an example of how you might like to visualize what each object’s data might look. Notice how ‘self’ is replaced with the objects name. I'm not saying this example diagram below is wholly accurate but it hopefully with serve a purpose in visualizing the use of self.
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 an object like this: When an object is made it uses the class as a template for its own data and methods. Without passing it's own name into the self parameter, the attributes and methods in the class would remain as 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, they can all keep track of their own data and methods.
See the illustration below:
When objects are instantiated, the object itself is passed into the self parameter.
Because of this, the object’s data is bound to the object. Below is an example of how you might like to visualize what each object’s data might look. Notice how ‘self’ is replaced with the objects name. I'm not saying this example diagram below is wholly accurate but it hopefully with serve a purpose in visualizing the use of self.
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 an object like this: When an object is made it uses the class as a template for its own data and methods. Without passing it's own name into the self parameter, the attributes and methods in the class would remain as 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, they can all keep track of their own data and methods.
See the illustration below:
answered Jun 28 '15 at 5:47
sw123456sw123456
2,1981824
2,1981824
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 8:31
3
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 8:48
3
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 9:18
2
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 9:23
3
This is how you explain stuff ! nice job :)
– penta
Nov 5 '17 at 9:44
|
show 2 more comments
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 8:31
3
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 8:48
3
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 9:18
2
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 9:23
3
This is how you explain stuff ! nice job :)
– penta
Nov 5 '17 at 9:44
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 8:31
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 8:31
3
3
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 8:48
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 8:48
3
3
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 9:18
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 9:18
2
2
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 9:23
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 9:23
3
3
This is how you explain stuff ! nice job :)
– penta
Nov 5 '17 at 9:44
This is how you explain stuff ! nice job :)
– penta
Nov 5 '17 at 9:44
|
show 2 more comments
I like this example:
class A:
foo =
a, b = A(), A()
a.foo.append(5)
b.foo
ans: [5]
class A:
def __init__(self):
self.foo =
a, b = A(), A()
a.foo.append(5)
b.foo
ans:
14
so vars without self is simply static vars of the class, like in java
– teddy teddy
Sep 7 '12 at 19:45
4
teddy teddy, you aren't entirely correct. The behavior (static or non-static like) depends not only onself
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
1
Actually, my question with this is why are you allowed to saya.foo
in the first example, rather thanA.foo
? Clearlyfoo
belongs to the class...
– Radon Rosborough
Aug 6 '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 0:25
1
@RadonRosborough Because in the first example,a
andb
are both labels (or pointers) forA()
(the class).a.foo
references theA().foo
class method. In the second example, though,a
becomes a reference to an instance ofA()
, as doesb
. Now that they are instances instead of the class object itself, self allows thefoo
method to operate on the instances.
– LegendaryDude
Jul 12 '17 at 17:07
add a comment |
I like this example:
class A:
foo =
a, b = A(), A()
a.foo.append(5)
b.foo
ans: [5]
class A:
def __init__(self):
self.foo =
a, b = A(), A()
a.foo.append(5)
b.foo
ans:
14
so vars without self is simply static vars of the class, like in java
– teddy teddy
Sep 7 '12 at 19:45
4
teddy teddy, you aren't entirely correct. The behavior (static or non-static like) depends not only onself
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
1
Actually, my question with this is why are you allowed to saya.foo
in the first example, rather thanA.foo
? Clearlyfoo
belongs to the class...
– Radon Rosborough
Aug 6 '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 0:25
1
@RadonRosborough Because in the first example,a
andb
are both labels (or pointers) forA()
(the class).a.foo
references theA().foo
class method. In the second example, though,a
becomes a reference to an instance ofA()
, as doesb
. Now that they are instances instead of the class object itself, self allows thefoo
method to operate on the instances.
– LegendaryDude
Jul 12 '17 at 17:07
add a comment |
I like this example:
class A:
foo =
a, b = A(), A()
a.foo.append(5)
b.foo
ans: [5]
class A:
def __init__(self):
self.foo =
a, b = A(), A()
a.foo.append(5)
b.foo
ans:
I like this example:
class A:
foo =
a, b = A(), A()
a.foo.append(5)
b.foo
ans: [5]
class A:
def __init__(self):
self.foo =
a, b = A(), A()
a.foo.append(5)
b.foo
ans:
answered Apr 26 '10 at 16:02
kamekame
6,3651975123
6,3651975123
14
so vars without self is simply static vars of the class, like in java
– teddy teddy
Sep 7 '12 at 19:45
4
teddy teddy, you aren't entirely correct. The behavior (static or non-static like) depends not only onself
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
1
Actually, my question with this is why are you allowed to saya.foo
in the first example, rather thanA.foo
? Clearlyfoo
belongs to the class...
– Radon Rosborough
Aug 6 '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 0:25
1
@RadonRosborough Because in the first example,a
andb
are both labels (or pointers) forA()
(the class).a.foo
references theA().foo
class method. In the second example, though,a
becomes a reference to an instance ofA()
, as doesb
. Now that they are instances instead of the class object itself, self allows thefoo
method to operate on the instances.
– LegendaryDude
Jul 12 '17 at 17:07
add a comment |
14
so vars without self is simply static vars of the class, like in java
– teddy teddy
Sep 7 '12 at 19:45
4
teddy teddy, you aren't entirely correct. The behavior (static or non-static like) depends not only onself
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
1
Actually, my question with this is why are you allowed to saya.foo
in the first example, rather thanA.foo
? Clearlyfoo
belongs to the class...
– Radon Rosborough
Aug 6 '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 0:25
1
@RadonRosborough Because in the first example,a
andb
are both labels (or pointers) forA()
(the class).a.foo
references theA().foo
class method. In the second example, though,a
becomes a reference to an instance ofA()
, as doesb
. Now that they are instances instead of the class object itself, self allows thefoo
method to operate on the instances.
– LegendaryDude
Jul 12 '17 at 17:07
14
14
so vars without self is simply static vars of the class, like in java
– teddy teddy
Sep 7 '12 at 19:45
so vars without self is simply static vars of the class, like in java
– teddy teddy
Sep 7 '12 at 19:45
4
4
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
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
1
1
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...– Radon Rosborough
Aug 6 '14 at 18:29
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...– Radon Rosborough
Aug 6 '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 0:25
You can call static members from instances of the object in most languages. Why is that surprising?
– Paarth
Oct 29 '14 at 0:25
1
1
@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
@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
add a comment |
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]
1
I wish Python sugarcoated the handlers as well as Ruby does.
– Cees Timmerman
Sep 21 '17 at 18:18
add a comment |
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]
1
I wish Python sugarcoated the handlers as well as Ruby does.
– Cees Timmerman
Sep 21 '17 at 18:18
add a comment |
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]
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]
answered Jun 22 '11 at 0:27
ninjageckoninjagecko
59.6k17112120
59.6k17112120
1
I wish Python sugarcoated the handlers as well as Ruby does.
– Cees Timmerman
Sep 21 '17 at 18:18
add a comment |
1
I wish Python sugarcoated the handlers as well as Ruby does.
– Cees Timmerman
Sep 21 '17 at 18:18
1
1
I wish Python sugarcoated the handlers as well as Ruby does.
– Cees Timmerman
Sep 21 '17 at 18:18
I wish Python sugarcoated the handlers as well as Ruby does.
– Cees Timmerman
Sep 21 '17 at 18:18
add a comment |
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"
add a comment |
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"
add a comment |
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"
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"
edited Dec 24 '13 at 22:23
Ry-♦
167k38339359
167k38339359
answered Apr 25 '10 at 20:31
PonkadoodlePonkadoodle
3,88722957
3,88722957
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
edited Apr 26 '10 at 14:09
answered Apr 25 '10 at 20:29
Matthew RankinMatthew Rankin
267k34103144
267k34103144
add a comment |
add a comment |
Python is not a language built for Object Oriented Programming unlike Java or C++.
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 method, which requires you to make a variable, which is 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 variable within a method, self will not work. That variable is simply existent 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 :).
+1 because of the distinction betweenstaticMethod()
andobjectMethod(self)
. I would like to add that in order to invoke the first, you would sayAnimal.staticMethod()
, whileobjectMethod()
needs an instance:a = Animal(); a.objectMethod()
– Laryx Decidua
Jul 24 '15 at 9: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
1
The only answer that makes sense! Thank you!!!!!!!!!!!!!!!!!!!!!!!
– john
Jul 25 '17 at 1:47
2
@ytpillai Irrelevant. Confusing and incorrect code should not be presented as an answer.
– Cees Timmerman
Sep 21 '17 at 18:34
1
def getAnimalName
to not clobber the string you're trying to return, andself
refers to the instance of the class, not any field inside of it.
– Cees Timmerman
Sep 21 '17 at 18:38
|
show 3 more comments
Python is not a language built for Object Oriented Programming unlike Java or C++.
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 method, which requires you to make a variable, which is 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 variable within a method, self will not work. That variable is simply existent 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 :).
+1 because of the distinction betweenstaticMethod()
andobjectMethod(self)
. I would like to add that in order to invoke the first, you would sayAnimal.staticMethod()
, whileobjectMethod()
needs an instance:a = Animal(); a.objectMethod()
– Laryx Decidua
Jul 24 '15 at 9: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
1
The only answer that makes sense! Thank you!!!!!!!!!!!!!!!!!!!!!!!
– john
Jul 25 '17 at 1:47
2
@ytpillai Irrelevant. Confusing and incorrect code should not be presented as an answer.
– Cees Timmerman
Sep 21 '17 at 18:34
1
def getAnimalName
to not clobber the string you're trying to return, andself
refers to the instance of the class, not any field inside of it.
– Cees Timmerman
Sep 21 '17 at 18:38
|
show 3 more comments
Python is not a language built for Object Oriented Programming unlike Java or C++.
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 method, which requires you to make a variable, which is 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 variable within a method, self will not work. That variable is simply existent 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 :).
Python is not a language built for Object Oriented Programming unlike Java or C++.
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 method, which requires you to make a variable, which is 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 variable within a method, self will not work. That variable is simply existent 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 :).
edited Sep 21 '17 at 18:39
answered May 25 '15 at 16:04
ytpillaiytpillai
2,2001833
2,2001833
+1 because of the distinction betweenstaticMethod()
andobjectMethod(self)
. I would like to add that in order to invoke the first, you would sayAnimal.staticMethod()
, whileobjectMethod()
needs an instance:a = Animal(); a.objectMethod()
– Laryx Decidua
Jul 24 '15 at 9: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
1
The only answer that makes sense! Thank you!!!!!!!!!!!!!!!!!!!!!!!
– john
Jul 25 '17 at 1:47
2
@ytpillai Irrelevant. Confusing and incorrect code should not be presented as an answer.
– Cees Timmerman
Sep 21 '17 at 18:34
1
def getAnimalName
to not clobber the string you're trying to return, andself
refers to the instance of the class, not any field inside of it.
– Cees Timmerman
Sep 21 '17 at 18:38
|
show 3 more comments
+1 because of the distinction betweenstaticMethod()
andobjectMethod(self)
. I would like to add that in order to invoke the first, you would sayAnimal.staticMethod()
, whileobjectMethod()
needs an instance:a = Animal(); a.objectMethod()
– Laryx Decidua
Jul 24 '15 at 9: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
1
The only answer that makes sense! Thank you!!!!!!!!!!!!!!!!!!!!!!!
– john
Jul 25 '17 at 1:47
2
@ytpillai Irrelevant. Confusing and incorrect code should not be presented as an answer.
– Cees Timmerman
Sep 21 '17 at 18:34
1
def getAnimalName
to not clobber the string you're trying to return, andself
refers to the instance of the class, not any field inside of it.
– Cees Timmerman
Sep 21 '17 at 18:38
+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()
– Laryx Decidua
Jul 24 '15 at 9:37
+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()
– Laryx Decidua
Jul 24 '15 at 9: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
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
1
1
The only answer that makes sense! Thank you!!!!!!!!!!!!!!!!!!!!!!!
– john
Jul 25 '17 at 1:47
The only answer that makes sense! Thank you!!!!!!!!!!!!!!!!!!!!!!!
– john
Jul 25 '17 at 1:47
2
2
@ytpillai Irrelevant. Confusing and incorrect code should not be presented as an answer.
– Cees Timmerman
Sep 21 '17 at 18:34
@ytpillai Irrelevant. Confusing and incorrect code should not be presented as an answer.
– Cees Timmerman
Sep 21 '17 at 18:34
1
1
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
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
|
show 3 more comments
Its use is similar to the use of this
keyword in Java, i.e. to give a reference to the current object.
class myClass: def myFunc(this, name): this.name = name
– LEM Adane
Oct 26 '12 at 12:01
add a comment |
Its use is similar to the use of this
keyword in Java, i.e. to give a reference to the current object.
class myClass: def myFunc(this, name): this.name = name
– LEM Adane
Oct 26 '12 at 12:01
add a comment |
Its use is similar to the use of this
keyword in Java, i.e. to give a reference to the current object.
Its use is similar to the use of this
keyword in Java, i.e. to give a reference to the current object.
edited Feb 27 '17 at 9:47
ChickenFeet
980817
980817
answered Aug 30 '12 at 16:37
Gaurav NishantGaurav Nishant
11112
11112
class myClass: def myFunc(this, name): this.name = name
– LEM Adane
Oct 26 '12 at 12:01
add a comment |
class myClass: def myFunc(this, name): this.name = name
– LEM Adane
Oct 26 '12 at 12:01
class myClass: def myFunc(this, name): this.name = name
– LEM Adane
Oct 26 '12 at 12:01
class myClass: def myFunc(this, name): this.name = name
– LEM Adane
Oct 26 '12 at 12:01
add a comment |
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
.
add a comment |
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
.
add a comment |
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
.
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
.
edited Dec 24 '13 at 22:24
Ry-♦
167k38339359
167k38339359
answered Aug 16 '13 at 17:23
dan-klassondan-klasson
8,05884068
8,05884068
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered Apr 25 '10 at 20:26
Ming-TangMing-Tang
10.2k63170
10.2k63170
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered Jan 12 '16 at 18:10
user441521user441521
2,1651457122
2,1651457122
add a comment |
add a comment |
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
add a comment |
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
add a comment |
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
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
answered Jan 12 '18 at 4:45
Akash KandpalAkash Kandpal
788818
788818
add a comment |
add a comment |
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.
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
2
@kmario23 You're response was from here: 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
add a comment |
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.
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
2
@kmario23 You're response was from here: 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
add a comment |
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.
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.
answered Nov 15 '14 at 7:54
kmario23kmario23
16.4k45869
16.4k45869
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
2
@kmario23 You're response was from here: 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
add a comment |
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
2
@kmario23 You're response was from here: 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
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
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
2
2
@kmario23 You're response was from here: 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
@kmario23 You're response was from here: 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
add a comment |
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).
add a comment |
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).
add a comment |
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).
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).
answered Aug 27 '15 at 7:31
skykingskyking
10.1k1339
10.1k1339
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
edited Aug 12 '18 at 10:20
answered Aug 1 '18 at 10:53
Bugs BuggyBugs Buggy
885822
885822
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
edited May 23 '17 at 12:18
Community♦
11
11
answered Jan 26 '14 at 18:11
TheEnglishMeTheEnglishMe
99831828
99831828
add a comment |
add a comment |
it's an explicit reference to the class instance object.
17
I don't think this helps richzilla to understand the reason behind it.
– Georg Schölly
Apr 25 '10 at 20:30
@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.
– BlueTomato
Oct 9 '17 at 14:51
add a comment |
it's an explicit reference to the class instance object.
17
I don't think this helps richzilla to understand the reason behind it.
– Georg Schölly
Apr 25 '10 at 20:30
@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.
– BlueTomato
Oct 9 '17 at 14:51
add a comment |
it's an explicit reference to the class instance object.
it's an explicit reference to the class instance object.
answered Apr 25 '10 at 20:24
SilentGhostSilentGhost
192k47263262
192k47263262
17
I don't think this helps richzilla to understand the reason behind it.
– Georg Schölly
Apr 25 '10 at 20:30
@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.
– BlueTomato
Oct 9 '17 at 14:51
add a comment |
17
I don't think this helps richzilla to understand the reason behind it.
– Georg Schölly
Apr 25 '10 at 20:30
@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.
– BlueTomato
Oct 9 '17 at 14:51
17
17
I don't think this helps richzilla to understand the reason behind it.
– Georg Schölly
Apr 25 '10 at 20:30
I don't think this helps richzilla to understand the reason behind it.
– Georg Schölly
Apr 25 '10 at 20:30
@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.
– BlueTomato
Oct 9 '17 at 14:51
@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.
– BlueTomato
Oct 9 '17 at 14:51
add a comment |
protected by Jon Clements♦ Apr 23 '13 at 8:26
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
92
You may find interesting this essay "Why explicit self has to stay" by Guido van Rossum: neopythonic.blogspot.com/2008/10/…
– unutbu
Apr 25 '10 at 20:35
12
See also "Why must 'self' be used explicitly in method definitions and calls": docs.python.org/faq/…
– unutbu
Apr 25 '10 at 20:38
31
"Which i understand, quite easily" --- Quite subjective, don't you think? What makes
@name
more intuitive thanself.name
? The latter, IMO, is more intuitive.– Santa
Apr 28 '10 at 0:12
11
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 6:59
8
I don't think "explicit is better than implicit" really explains this design choice well.
@foo
andself.foo
are equally explicit as no implicit resolution needs to occur (e.g. in C++, instance members can be "implicitly" accessed without "explicitly" using namespaces). The only difference is that Ruby introduces a new semantic (@), while Python does not. Whether or not a new semantic was worth the amount of verbosity avoided is purely subjective. Though, it should be noted that most modern languages choose to introduce a concept here (e.g. php's $this, JS's this).– Jing
Jun 14 '14 at 0:09