3

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?

Kohei Sanno
  • 31
  • 1
  • 2
  • 2
    It means that where `self` occurs inside `{}` in the format string, it refers to object referenced by the `self` variable. – khelwood Jul 20 '18 at 13:29

3 Answers3

2
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

rafaelc
  • 57,686
  • 15
  • 58
  • 82
1

self is being used in two separate contexts; one as a local variable in the method, and the other as an identifier in the format string. You could rename either one or both and get the same result:

return "a {c.color} car".format(c=self)

or

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

or even

def __str__(foo):
    return "a {bar.color} car".format(bar=foo)

My preference would be for the first alternative of the three, as there's no good reason to violate the convention that the first parameter to an instance method be named self.

chepner
  • 497,756
  • 71
  • 530
  • 681
0

The first self (left of the = sign) refers to the self string in 'a {self.color} car' (you can call it like you want).`

The second self (right of the = sign) refers to the first argument of the __str__() method, which is always a reference to the current instance of the class. In your example, this will be replaced by my_car.

NiGiord
  • 57
  • 6
  • 2
    *The second self (right of the = sign) is a Python keyword* - it's not a keyword... it's just a name which is by convention `self` - it could be anything a developer chooses... – Jon Clements Jul 20 '18 at 13:46