working with classes, inheritance, _str_ returns and a list

Erik python at
Sun Jan 15 16:27:58 EST 2017


On 15/01/17 19:58, David D wrote:
> I am creating a parent class and a child class.  I am inheriting from
> the parent with an additional attribute in the child class.  I am
> using __str__ to return the information.  When I run the code, it
> does exactly what I want, it returns the __str__ information.  This
> all works great.
> 1) I want what is returned to be appended to a list (the list will be
> my database) 2) I append the information to the list that I created
> 3) Whenever I print the list, I get a memory location
> So how do I take the information that is coming out of the child
> class (as a __str__ string), and keep it as a string so I can append
> it to the list?


> Here is where it goes wrong for me
> allcars.append(car1)

This adds the object (of the child or parent class) to the list. If you
_really_ want the *string* returned by __str__() to be appended to the
list then you would do:


(The str() function returns what the object's __str__() method returns
if it has one - otherwise it will return SOME sort of string
representation of your object, but you can't rely on the format of that).

I'm a bit confused though as to why you would want to create that object
only store its __str__() value and discard the object itself.


More information about the Python-list mailing list