What is self?


What is self?


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.


Doesn’t the name refer to the current car model as well? What am I missing?

1 Like

The current car model is one attribute of the car instance. self refers to the instance in context scope, that is the current instance, i.e., the instance upon which the call is made.

my_car = Car('Toyota Corolla', 'crimson', '88')

When we access the attributes or methods of this instance, self becomes my_car so that this instance is the context.


Thus, is “self” a function in Python or just a convention the community has accepted?
Could it be “xxxx”?

class my_car(object):
  def __init__(xxxx,car_name):
    xxxx.car_name = car_name

Yes, you have hit on something. self is the widely accepted and recognizable variable name. As you’ve discovered, any name will do, even good old, this.