如何在循环中为类实例属性赋值

时间:2017-10-10 06:28:42

标签: python class loops oop

class User:
    num_of_user = 0
    def __init__(self,name):
        self.name = name
        User.num_of_user += 1

user_1 = User('A')
user_2 = User('B')
....

class Value(User):
    def __init__(self,name,value):
        User.__init__(self, name)
        self.value = value

# --> user_1.value = read a new manual input
# --> user_2.value = read a new manual input
....

我不熟悉如何在Class中正确显示实例/属性。

如何在For循环中写上面的注释?

2 个答案:

答案 0 :(得分:2)

这样做,

class User:
    num_of_user = 0
    def __init__(self,name):
        self.name = name
        User.num_of_user += 1

names = ['A','B','C','D']
users = []
for name in names:
    users.append(User(name))

for user in users:
   user.value = 'input from user'

答案 1 :(得分:1)

将所有创建的User_X实例添加到List / Array(users / userList)并迭代它。

# step by step
user_1 = User("A")
user_2 = User("B")
user_3 = User("C")

users = []
users.append(user_1)
users.append(user_2)
users.append(user_3)

# Better way with less instances
users = [User("A"), User("B"), User("C")]

现在您可以添加一个简单的迭代:

for user in users:
  user.value = <SOME INPUT>