简体   繁体   中英

Python class objects appending to list

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>]

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>}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM