How is Python – .format(self=self) used? … here is a solution to the problem.
How is Python – .format(self=self) used?
I see a piece of code that looks 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 self=self used in the str method work?
Solution
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 can also be
'a {obj.color} car'.format(obj=self)
Self on the left in self=self
refers to the actual value that will be entered. In this case, the object is passed as a parameter. In other words, it can also be
def __str__(obj):
return 'a {self.color} car'.format(self=obj)
So, for the overall View, you have
def __str__(value_passed):
return 'a {value_to_change.color} car'.format(value_to_change=value_passed)
Why use self
now?
This is just a convention used in Python programming. Python automatically passes an object to its instance method, which is a pointer to itself. See also this question for more information