0

I am taking in user input and creating objects with it. So I have a list of acceptable object names (A-E). What I figured I could do was pop(0) and use the return value as the name of the object. This way there is never a duplicate object name upon entry. Here is what I have so far I just cannot figure out how to assign the popped value to the name of the object properly.(Net is a defined class at the start of the program)

userIP = None

name_list = ['A', 'B', 'C', 'D', 'E']

while True:
    if userIP == 'end':
        break
    userIP = input("Enter IP (type 'end' to exit): ")
    userMask = input("Enter Mask: ")
    name_list.pop(0) = Net(userIP, userMask)
    print("The object just created would print here")

2 Answers2

5

Put the results in a dictionary. Don't try to create variables with specified names. That way lies madness.

net_dict = {}

# ...

name = name_list.pop(0)
net_dict[name] = Net(userIP, userMask)
print(net_dict[name])

If you have them in a container, you may find you don't actually need the names. What are the names for, in other words? If the answer is just "to keep them in some order," use a list:

net_list = []

# ...

net_list.append(Net(userIP, userMask))
print(net_list[-1])
kindall
  • 178,883
  • 35
  • 278
  • 309
  • Thanks for your help. The names are going to be used with further user input after they enter end the Net class has functions in it to evaluate the subnet masks and IPs for different things (overloads of __and__ and __or__). So the user will enter A*B for example and then the function will evaluate if the two are on the same subnet. – user3002598 Nov 19 '14 at 17:15
  • In that case you definitely want to use a dictionary. Then you an pass that dict to `eval()` as your globals (second argument) so that `A*B` can be evaluated using that dictionary as the variables. – kindall Nov 19 '14 at 17:36
1

I just cannot figure out how to assign the popped value to the name of the object properly

It's not easy to do that, because it's not very useful to do that. What if you do get it to work, and you want to use the thing later on?

name_list.pop(0) = Net(userIP, userMask)
print ?.userMask

What do you put for the ? when you have no idea which variable name was used?

The right approach to this is @kindall's answer, or similar. But it is possible ( How can you dynamically create variables via a while loop? ) but not recommended.

Community
  • 1
  • 1
TessellatingHeckler
  • 27,511
  • 4
  • 48
  • 87
  • Thanks for your input. I am not much of a programmer (at all). Pop just came to mind because it was a way I could get the name alone while also removing it from the list. I understand now why this wouldn't work. – user3002598 Nov 19 '14 at 17:17