I've been teaching myself Python using the Python Crash Course book, and now that I've reached the end of it I've been going through various tutorial websites to practice/supplement what I've learned. However, I've run into something strange.
As far as I can see, the Python Crash Course book does not mention __str__(). When I started looking at some class tutorials, as that's something I'm struggling with, I've run into examples where they use a method called __str__().
I'm shaky as to what it does, and I'm even more confused by the examples. I see one on https://www.w3schools.com/python/python_classes.asp which uses the following code:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name}({self.age})"
p1 = Person("John", 36)
print(p1)When run, it returns John 36. Then there's another example where the __str__() method is not used, and it returns <__main__.Person object at 0x15039e602100>.
Okay, fine. So I need to use __str__() for this to work. But in the Python Crash Course, it shows an example with a similar class, and it does not use a __str__() method, and it works fine:
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self. year = year
def get_descriptive_name(self):
long_name = f"{self.year} {self.make} {self.model}"
return long_name.title()
my_new_car = Car("Audi", "a4", "2024")
print(my_new_car.get_descriptive_name())This returns "2004 Audi A4". But it does not use a __str__() method. Why?