Consider this example:
class MyClass:
def func(self, name):
self.name = name
I know that self
refers to the specific instance of MyClass
. But why must func
explicitly include self
as a parameter? Why do we need to use self
in the method's code? Some other languages make this implicit, or use special syntax instead.
For a language-agnostic consideration of the design decision, see What is the advantage of having this/self pointer mandatory explicit?.
To close debugging questions where OP omitted a self
parameter for a method and got a TypeError
, use TypeError: method() takes 1 positional argument but 2 were given instead. If OP omitted self.
in the body of the method and got a NameError
, consider How can I call a function within a class?.
The reason you need to use self.
is because Python does not use special syntax to refer to instance attributes. Python decided to do methods in a way that makes the instance to which the method belongs be passed automatically, but not received automatically: the first parameter of methods is the instance the method is called on. That makes methods entirely the same as functions, and leaves the actual name to use up to you (although self
is the convention, and people will generally frown at you when you use something else.) self
is not special to the code, it's just another object.
Python could have done something else to distinguish normal names from attributes -- special syntax like Ruby has, or requiring declarations like C++ and Java do, or perhaps something yet more different -- but it didn't. Python's all for making things explicit, making it obvious what's what, and although it doesn't do it entirely everywhere, it does do it for instance attributes. That's why assigning to an instance attribute needs to know what instance to assign to, and that's why it needs self.
.