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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With