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.
I like this example:
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 byself.user_type_name
.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.The following excerpts are from the Python documentation about self:
For more information, see the Python documentation tutorial on classes.
Let's say you have a class
ClassA
which contains a methodmethodA
defined as:and
ObjectA
is an instance of this class.Now when
ObjectA.methodA(arg1, arg2)
is called, python internally converts it for you as:The
self
variable refers to the object itself.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)
, wherevar
was used in the__init__(var,[...])
You should take a look at
cls
too, to have the bigger picture. This post could be helpful.