What is self?


#1

Question

What is self?

Answer

self’s purpose may not seem very obvious at first, especially if you’ve never used an object-oriented programming language before!
Try to imagine a class named Car that has the basic structure that all cars share in common. It defines a basic acceleration behavior, but not how fast it accelerates or what the max speed is, as that varies from car to car. It defines a start method, but not the specifics of how it starts, as that varies as well.
Now imagine that we’ve created Car objects of all the models we can think of. So now we have a mustang object, a tesla_model_x object, etc. Upon creation we can now specify how a particular model accelerates or starts. Inside of our Car’s __init()__ method we use self to refer to the current car model so we can assign values like top speeds and whatnot.


FAQ: Learn Python - Introduction to Bitwise Operators - Let's Not Get Too Selfish