Attribute name for a self

Is there an attribute name for a self? I mean, in functions, it looks like everything has an attribute name and assigned value. We can even abbreviate it because we know that on a certain position (like 0 position), there is always a certain attribute. So, for example, we will write window or parent instead of master = window or master = parent in Tkinter. So is there *something* = self?

From class theory, self references the handle (name given to object when class is instantiated) of the object you create with the class.

for example:

class OneCar:

    def __init__(self, car, color):

        self.car = car
        self.color = color

car1 = OneCar('sedan', 'blue')  # Create object by way of instantiating the class

So, in this particular example, self references car1. Or self = car1. If you make multiple cars with this class, you will have to create unique names to reference which car you are talking about or referencing. In a real world example, if you have ever seen cars being produced off of an assembly line, they are all identical except maybe for the paint color. Once they are sold to the public, they each will have to have a unique identifier. This is the Vehicle Identification Number (VIN). In the case above, the unique identifier is car1 which is the self in order to get access to the attributes of the class.

Hi Jan,

JS has self as a special name for this on functions. In Python “self” is just a convention for the first variable of an instance method. It may cause opinionated code checking tools to complain, and it would confuse other Python coders, but you can call it what ever you want instead of self.

I’ve also tried to write a function, that has some sort of configuration or a basic state like a cache (beyond what’s provided by functools decorators).

I find it’s usually simplest to mimmick a function, and just give it an explicit self, by writing a class with a __call__ dunder method, and exposing an instance of it.

It’s not entirely clear what you are asking, but there is no one-to-one correspondence between function arguments and the attributes of any particular object. Some methods (like __init__) may use arguments to define attributes via ordinary attribute assignment, but even then the parameter is an implementation detail of the function. There’s no implied correspondence between any one parameter and an attribute:

def __init__(self, a, b):
    self.a = b
    self.b = a

This silly example demonstrates two thing:

  1. The parameter self is not associated with an attribute of any object; it is an object.
  2. The parameter a is not associated with the attribute a; its value is used to define another attribute b. (And similarly for the parameter b.)
1 Like