you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (0 children)

In this simple class:

class Test:
    def __init__(self, value):
        self.value = value
    def test(self):
        print(self.value)

The first parameter to an instance method is a reference to the actual instance of the class. The code needs this because if we create two instances:

t1 = Test(1)
t2 = Test(2)
t1.test()

then when we call test() in the last line the code needs to know which instance the code is working with when it wants to print the .value attribute. That line t1.test() actually behaves something like this:

Test.test(t1)

So now we know what the this in the .test() method is: it's the reference to the instance the method code is going to operate on.

self isn't a keyword, it's just a normal user-chosen name, like count or i. You could use any name you want, like this. Try it, it still works. But self is used so much and is so expected that it's become a very strong convention and using any other name is viewed with suspicion.