Can anyone explain this to me? class Car: color = 'gray' def describeCar(self): return 'A cool ' + Car.color + ' car' def describeSelf(self): return 'A cool ' + self.color + ' car' lola = Car() lola.color = 'plaid' why lola.describeCar() prints 'A cool gray car' rather than 'A cool plaid car'?
is this python?
yes
because you changed the `color` attribute of `lola` to `'plaid'` with the line ``` lola.color = 'plaid' ``` When you initialized `lola = Car()` you set the attribute `lola.color` to the default value, which is `'grey'`, but you then changed that attribute `'plaid'` as I stated above. This is not how you are actually supposed to change attribute values, by the way, but I'm sure you will learn a better way soon.
I didn't write this code, it was an exercise on a website and I was supposed to answer what the code will print. I thought it was "A cool plaid car" but the answers turned out to be "A cool gray car"
In the method "describedCar" is used "Car.color" which is a class attribute, "Car.color" is not same as "self.color" and is not part of the "lola" object and because of that can't be changed through the "lola.color" object attribute.
http://www.toptal.com/python/python-class-attributes-an-overly-thorough-guide
@tpetkovski is correct I both misunderstood the question and gave a bad answer, sorry
Thank you
Join our real-time social learning platform and learn together with your friends!