简体   繁体   中英

Appending to a class instance attribute in python

I have a list of class instances, and I want to append separate items to an attribute for each. However, I ended up appending each item to the attribute on every instance in the list. Example code below:

class example:
    def __init__(self):
        example.xlist = []

classes = [example(), example(), example()]
i=0
for instnce in classes:
    instnce.xlist.append(i)
    i+=1
print("1st list:", classes[0].xlist)
print("2nd list:", classes[1].xlist)
print("3rd list:", classes[2].xlist) 

I want the output to be:

1st list: [0]  
2nd list: [1]  
3rd list: [2]

but instead I get:

1st list: [0, 1, 2]  
2nd list: [0, 1, 2]  
3rd list: [0, 1, 2]

any ideas on what is happening / what I can change to get the desired output?

The problem is in your constructor when you create the new list. Instead of creating example.xlist , you should try using self.xlist instead. In Python, the self keyword, refers to the specific instance and not the general object.

If we apply this change to your sample code, we get:

class example:
    def __init__(self):
        self.xlist = []

classes = [example(), example(), example()]
i=0
for instnce in classes:
    instnce.xlist.append(i)
    i+=1
print("1st list:", classes[0].xlist)
print("2nd list:", classes[1].xlist)
print("3rd list:", classes[2].xlist) 

This code produces the correct output.

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