4

I am learning python right now and I am learning about classes. I am confused about the purpose of self and more specifically why I have to write self.make = make, etc.

Here is my example:

class Car():

    def _init_(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

    def get_name(self):
        long_name = str(self.year) + ' ' + self.make + ' ' + self.model
        return long_name.title()

To me, this looks like you are just setting a variable to itself which doesn't make sense to me. What is the purpose of this statement?

Brandon Kheang
  • 597
  • 1
  • 6
  • 19
  • That's all you need to know: [the self variable in python explained](https://pythontips.com/2013/08/07/the-self-variable-in-python-explained/) – Yaroslav Surzhikov Sep 13 '17 at 03:34

2 Answers2

2

self is representative of an instance of that class. So in the constructor init what is happening is that "self" == the object copy created when the constructor was called.

You can think of it this way, a constructor makes a new object. As soon as we have a new object, we want to do something with it, how do we refer to that object? As self.

Important Note: Self could be anything, it could have just as easily been fish, and it would then be fish.make, fish.model, fish.year. The only important thing about the keyword self is that it is the FIRST argument to the constructor.

jmercouris
  • 348
  • 5
  • 17
0

You are taking make, an argument which will disappear when the initiator finishes, and copying it to self.make, an instance attribute which belongs to your new object and will remain available for the next time you want to refer to it.

Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99