Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of doing self.something = something [duplicate]

Tags:

python

class

self

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?

like image 310
Brandon Kheang Avatar asked Oct 18 '25 00:10

Brandon Kheang


1 Answers

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.

like image 193
jmercouris Avatar answered Oct 19 '25 14:10

jmercouris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!