1

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>]
13
  • 2
    Well, the problem is the missing __str__ or __repr__ method; without is, that's just how Python represents those instances. Apart from that, your code works correctly. Commented Jan 16, 2019 at 15:25
  • There isn't really a way to do this. Think about it like this: What if you initialized myList1 like myList1 = [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. Commented Jan 16, 2019 at 15:25
  • Those two items are exactly r and r1: just their string representation (which defaults to this, since you haven't defined a string representation yourself for the class). Commented Jan 16, 2019 at 15:26
  • 1
    There's nothing wrong here: you are appending instances of 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__. Commented Jan 16, 2019 at 15:26
  • 1
    r and r1 are 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. Commented Jan 16, 2019 at 15:28

1 Answer 1

1

As pointed by others in comments.In your code at the moment you are getting the expected result as r and r1 are the instances of the class. In case you want to differentiate your instances on the basis of name and want to return the same you can pass name argument and define __repr__ to represent your output when str(instance) is being called. Just giving you a heads up:

class Robot():
    """Test class"""
    def __init__(self, age, name):
        self.age = age
        self.name = name

    def __repr__(self):
        return self.name

r = Robot(10,'r')
r1 = Robot(15,'r1')

mylist1 = [r, r1]
mylist2 = []

for item in mylist1:
    mylist2.append(item)
print(mylist2)

Result:

[r, r1]

Otherway could be to use a dictionary for mapping

class Robot():
    """Test class"""
    def __init__(self, age,name):
        self.age = age
        self.name=name

r = Robot(10,'r')
r1 = Robot(15,'r1')

mylist1 = [r, r1]
d={}

for item in mylist1:
    d[item.name]=item
print(d)

Output

{'r': <__main__.Robot instance at 0x0000000010BAD708>, 'r1': <__main__.Robot instance at 0x0000000010BAD148>}
Sign up to request clarification or add additional context in comments.

2 Comments

Right, now do add a bit more explanation to this. Don't just give code. Explain why this works, why theirs doesn't.
This article will make everything clear

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.