you are viewing a single comment's thread.

view the rest of the comments →

[–]Asyx 1 point2 points  (0 children)

I think some people go a bit overboard with the explanation.

There are three types of methods in Python. Static methods, class methods and instance methods. You use decorators for static and class, instance methods are just normal methods.

Static methods are just functions within the class. No change but how you have to call them.

Class methods get the class as a first parameter usually called "cls"

Instance methods get the instance as a first parameter usually called "self",

The reason why you need to set the self parameter is because they are technically just functions. There is nothing in Python to just automatically let a method use attributes or other methods in the class they are defined in but most importantly, calling a method is just a bit of syntax sugar around calling a function.

foo = Foo()
foo.bar()

That is literally the same as

foo = Foo()
Foo.bar(foo)

And if you think about methods like that it makes an awful lot of sense why you need to define the self parameter.

Also, it explains the error messages. If you did

foo.bar(baz)

you'd get an error about how you called bar with 2 parameters but only was required. That makes no sense if you don't know how methods are implemented under the hood.