Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Can somebody explain the "self" method?

+8 votes
asked Oct 10, 2022 by Eidnoxon (5,160 points)
Hi! I understand the self method a little bit, but it's good if somebody would explain it to me. I was never so simular with the self method. So if somebody can help, can you tell me everything about the self method? Please, It would help me a lot.

1 Answer

+1 vote
answered Oct 11, 2022 by Peter Minarik (88,130 points)
edited Oct 11, 2022 by Peter Minarik

You can read a bit more about self here.

The self variable (it's not a method, it's a parameter passed to your function, a variable in your code) is used to reference the current instance of your class.

Imagine you have a class Dog as below:

class Dog:
  def __init__(self, name, breed):
    self.name = name
    self.breed = breed

  def eat(self, food):
    print(f"{self.name} is eating {food}.")

Let's assume we have multiple instances of this Dog class.

dog1 = Dog("Butch", "Bulldog")
dog2 = Dog("Stella", "Poodle")

Now, if we want these dogs to eat something, we'd do something, like this.

dog1.eat("a bone")
dog2.eat("dog food")

Without having the self reference, in the Dog.eat() function we would have no idea which dog is eating. So we have the self reference to be able to tell which dog we talk about, so we can access fields such as name or breed (the latter is not used in the above example, but you could easily include it in the eat() or any new functions).

Other languages, such as C++, Java, C# have the this reference which fulfils a similar role.

Please note, that in Python, you can use any name, not just self (so you could call it this as well, or me, or anything really), but it must be the first argument of your function when you declare it. However, you do not need to pass this argument to your function when you're calling it (the language will do it automatically based on the instance you're calling the function on).

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.