I have a list of class objects that I would like to distribute to other lists as objects and then these lists should be called to provide interaction with the objects within.
The issue that I cannot overcome at the moment is when trying to append the objects with a for loop from the first list to the second one and instead getting the new list populated with the class objects I get their pointers to the memory.
This is currently running on Python 3.x if any difference.
I have seen some cases where the suggestion is to play with __str__ and
__repr__ but I don't come to a solution for my case.
class Robot():
"""Test class"""
def __init__(self, age):
self.age = age
r = Robot(10)
r1 = Robot(15)
mylist1 = [r, r1]
mylist2=[]
for item in mylist1:
mylist2.append(item)
print(mylist2)
I would expect to get something like [r, r1]
This is the result I get instead:
[<__main__.Robot object at 0x000001285CEE33C8>, <__main__.Robot object at 0x000001285CEE3748>]
__str__or__repr__method; without is, that's just how Python represents those instances. Apart from that, your code works correctly.myList1likemyList1 = [Robot(10), Robot(15)]. What should it print? The variable names aren't a part of the object. They're a separate label associated with the object. The objects don't know what variables names they've been given.randr1: just their string representation (which defaults to this, since you haven't defined a string representation yourself for the class).Robot, which are indeed located elsewhere in memory, and you only have pointers to them. This is how Python works. If you would like the string representation of these objects to be different, read about__repr__.randr1are variable names. They are not the robots themselves. They are just labels, post-it nodes stuck on the robots, and you can add as many of those post-it notes as you want. But you are adding the robots themselves to the list, not those names. See nedbatchelder.com/text/names.html for more information on how Python names work. If you want your robots to be shown in a list with a name, you need to explicitly give the robots names (as a attribute of the robot itself), and use__repr__to create a string to be shown when printing a list, where you include the names.