0

this is an example code from a book:

class Car():

    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

    def describe(self):
        long = str(self.year) + ' ' + self.make + ' ' + self.model
        return long.title()


mycar = Car('audi', 'a4', 2016)

print(mycar.describe())

i was thinking if i could make describe() do the same thing, but be more dynamic. and made a change:

class Car():

    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

    def describe(self):
        l = str(''.join(str([getattr(self, a) for a in dir(self) if not a.startswith('__')])))
        print(l)

mycar = Car('audi', 'a4', 2016)
mycar.describe()

I thought the code for describe() made perfect sense but the output is a little unexpected..

above code output:

─$ python3 carclassup.py
[<bound method Car.describe of <__main__.Car object at 0x7f0f5abaa8e0>>, 'audi', '14', 2016]
  1. Why is the output showing in a list? I tried to str() but it still outputs in list.

  2. What is <bound method Car.describe of <__main__.Car object at 0x7f0f5abaa8e0>>? I would like it not to be output.

  • "Why is the output showing in a list? " Because you applied `str` to the entire list, not to its elements; and then tried to `join` the single string, which then iterates over individual characters. "What is "..."" It is exactly what it says it is: the `.describe` method on the instance, which is *also an attribute*. I linked duplicate questions aimed at addressing both parts of the problem. Please note that in general you are expected to ask *one* question at a time. – Karl Knechtel Apr 25 '21 at 16:27
  • @KarlKnechtel it **is** one question. One question with two points – poweredbycocaine Apr 25 '21 at 16:31

0 Answers0