Difference in using self and this in python

87 Views Asked by At

Well, I am a newbie in Python and I am not able to understand the difference in using self and this keywords in Python. This is the code that uses self as parameter :

  class restaurant():
        bankrupt = False
        def open_branch(self):
            if not self.bankrupt:
                print("branch open")
    x=restaurant()
    print(x.bankrupt)
    y=restaurant()
    y.bankrupt=True
    print(y.bankrupt)

And this is the code that uses this as parameter :

class restaurant():
    bankrupt = False
    def open_branch(this):
        if not this.bankrupt:
            print("branch open")
x=restaurant()
print(x.bankrupt)
y=restaurant()
y.bankrupt=True
print(y.bankrupt)

Both these approaches gave me the same output. So I m not able to understand why we use self when this solves our problem. Maybe my interpretation of self is wrong. I looked a lot of internet stuff but did not found anything relevant. Can anyone please solve my issue.

2

There are 2 best solutions below

0
On

It is mentioned in Python document:

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.

0
On

Using the name self is just a (strong) convention. You are free to use any name instead, as long as you are constant. It is highly recommended to use self though.

In general, Python gives you a lot of freedom doing things the way you like. On the other hand, there are many conventions like how to name you variables (compare PEP8). In 99% of the cases it is best to adhere to this conventions. But if you a 1% case, you can do it differently. I have never seen a case for not using the name self though.

PEP8 recommends the use of self:

Always use self for the first argument to instance methods.