0
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
....

I am not familiar with how to present instances/attributes correctly in Class.

How to write above comment in a For loop?

0

2 Answers 2

2

This will do,

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'
Sign up to request clarification or add additional context in comments.

3 Comments

Why do you add globals to the mix for free where they are not even needed? You made your code more complex and suggest to use a feature that should only be used when you know what you are doing, Use a normal temporal variable or just append it directly.
I agree. i use globals very carefully(thats why i already mentioned it), but what if he needs to create many variable (hundreds of variable). this is easy, if you know what you are doing.
replace the 2 lines inside the loop with object_list.appen(User(v)) and you can now delete the glo = globals() and even simplify the loop to for v in Name: as you do not use the enumeration any more. Additionally, you should never use caps letter for variable names, you should change Name to names as it is a list of names. I will suggest an edit on your post so that you can accept it.
1

Add all created User_X instances to a List/Array (users/userList) and iterate through it.

# 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")]

Now you can add a simply iteration like:

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

2 Comments

how to make users.append() in a loop also?
@LiDong users = map(User, ["A", "B", "C"])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.