Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is .format(self=self) used?

Tags:

python

class

I saw a piece of code that was like this:

class Car:
    def __init__(self,color,mileage):
        self.color = color
        self.mileage = mileage

    def __str__(self):
        return 'a {self.color} car'.format(self=self)

my_car = Car('blue', 13585)
print(my_car)

How does the self=self that is used in the str method work?

like image 579
Kohei Sanno Avatar asked Jun 23 '26 11:06

Kohei Sanno


1 Answers

def __str__(self):
        return 'a {self.color} car'.format(self=self)

The first self in self=self refers to what the format function will change in your string. For example, it could also be

'a {obj.color} car'.format(obj=self)

The left-hand side self in self=self refers to the actual value that will be input. In this case, the object passed as argument. In other words, it could also be

def __str__(obj):
        return 'a {self.color} car'.format(self=obj)

Thus, for an overall view, you have

def __str__(value_passed):
        return 'a {value_to_change.color} car'.format(value_to_change=value_passed)

Now why to use self?

It is just a convention used in python programming. Python passes to its instance methods automatically an object that is a pointer to itself. Can also check this question for further info

like image 199
rafaelc Avatar answered Jun 24 '26 23:06

rafaelc