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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With