简体   繁体   English

如何在循环中分配 class 属性 Python

[英]How to assign class attributes in a loop Python

So I have a list:所以我有一个清单:

names = [“Bob”, “Guy”, “Super”, “Man”]

I am trying to use a loop to assign Bob Guy as the firstname and lastname of user1, the next time the loop runs I want it to assign Super Man as the firstname and lastname of user2.我正在尝试使用循环将 Bob Guy 分配为 user1 的名字和姓氏,下次循环运行时,我希望它分配 Super Man 作为 user2 的名字和姓氏。 I am using a class and the way I have set this up is by having a placeholder variable that grabs the 0 and 1 indexes of the list, and the next time to loop runs it grabs the 2 and 3 indexes.我正在使用 class 并且我设置它的方式是使用一个占位符变量来获取列表的 0 和 1 索引,并且下次循环运行它会获取 2 和 3 索引。 This works, however the problem is that my line says user1 = ClassName(names[placeholder var]) .这可行,但问题是我的行说user1 = ClassName(names[placeholder var]) Meaning that each time the loop runs it is reassigning user1.这意味着每次循环运行时都会重新分配 user1。 Is there a way to change the name of “user1” to “user2” to “user3” (each time the loop runs) so it assigns the firstname and lastname attributes to my class as a new object for each person?有没有办法将“user1”的名称更改为“user2”到“user3”(每次循环运行时),以便将名字和姓氏属性分配给我的 class 作为每个人的新 object? Thanks for any help.谢谢你的帮助。

I don't think its possible to assign variables the way u want from loop.我认为不可能按照你想要的方式从循环中分配变量。 You can use list to store user object This should satisfy you problem:您可以使用列表来存储用户 object 这应该可以满足您的问题:

names = ['Bob', 'Guy', 'Super', 'Man']
users = []
for i in range(0,len(names), 2):
    # print(names[i], names[i+1])
    user = ClassName(names[i], names[i+1])
    users.append(user)  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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