[英]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: 我想将这些参数分配给10个几乎相同的物体,如:
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: 并且可以改变,比如说,身体3的参数L从1到2:
body[3].L = 2
Thank you very much for the help. 非常感谢你的帮助。
Note that body
is a class. 请注意, body
是一个类。 Using body[i]
suggests you may be intending to use body
as a list. 使用body[i]
建议您可能打算将body
用作列表。 If you want to create a list of 10 instances of body
, do not name the list body
as well. 如果要创建10个body
实例的列表,请不要将列表body
命名。 You could instead name the list bodies
and define it with a list comprehension : 您可以改为将列表命名为bodies
,并用它定义列表理解 :
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 . 顺便说一下, PEP8样式指南建议所有类都遵循CapWords惯例 。 So to conform with the convention, body
should be Body
. 所以为了符合惯例, body
应该是Body
。 By following this convention, everyone reading your code will understand immediately what is a class and what is not. 按照这个惯例,每个阅读代码的人都会立即理解什么是类,什么不是。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.