简体   繁体   中英

Python create objects in for loop

I have a class to assign some parameters:

class body:
    def __init__(self, name, number, L):
        self.name = name
        self.number = number
        self.L = L

And I would like to assign these parameters to 10 almost equal bodies like:

for i in range(0, 10):
    body[i].name = "test_name"
    body[i].number = i
    body[i].L = 1.

And to be able to change, lets say, the parameter L of body 3 from 1 to 2:

body[3].L = 2

Thank you very much for the help.

Note that body is a class. Using body[i] suggests you may be intending to use body as a list. If you want to create a list of 10 instances of body , do not name the list body as well. You could instead name the list bodies and define it with a list comprehension :

bodies = [body("test_name", i, 1.) for i in range(0, 10)]
bodies[3].L = 2

By the way, PEP8 Style Guide recommends all classes follow the CapWords convention . So to conform with the convention, body should be Body . By following this convention, everyone reading your code will understand immediately what is a class and what is not.

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