0

What I want to achieve: I want to a user to be able to create their own variable names to initialize a class. For example:

class User(self, x, y):
    self.x = x
    self.y = y

username = User

How can I make it so that the user controls what the variable initializing the class is called?

For example, my name is Johan. How could I make it so that:

johan = User

A more specific way of phrasing this question:

How can I take user input as a string, and create a variable named after that string?

Johan
  • 23
  • 4
  • 1
    First of all, that class declaration and instantiation aren't okay. Secondly, why would you want to dynamically name variables? If you're just looking for a way to name the instance of the class then you can add a name attribute. – Wright Mar 10 '18 at 22:40
  • 2
    What are you *really* trying to achieve, and why? The reason I ask is, if a user inputs a name, why would they care about the name of the variable name used to point to the Class ? – jpp Mar 10 '18 at 22:41
  • Yeah just throwing out a random example for the question... I'm more curious if what I'm asking is at all possible. – Johan Mar 10 '18 at 22:44
  • @jpp I guess my use-case would be referencing a user-generated instance later on in the code. Actual names aside, let's say that when a user created an account on my service, their instance of the User class is named user1. If someone else signs up after them, they would be "user2". But to name the class user1 and then user2, this implies there's something iterating over all the numbers from 1 to infinity and appending them to the string 'user'. I can build this, but python won't let me do it because you can't assign a class to a variable name that's yet to be defined. – Johan Mar 10 '18 at 22:48
  • @Johan, as per marked duplicate, use a dictionary. – jpp Mar 10 '18 at 22:49
  • @jpp Yep, just noticed that. thanks for attempting to answer. – Johan Mar 10 '18 at 22:50
  • Yes. You can ask for user input for a parameter that you have in a class/function. I created a test function and asked the user for input and set x/y equal to the users input. I will post it below – Simeon Ikudabo Mar 10 '18 at 22:55
  • def user(x, y): x = x y = y y = input("What is your name?: ") x = input("Call this variable whatever you want: ") – Simeon Ikudabo Mar 10 '18 at 22:56
  • It's hard to post this in comments however, but asking for user input and setting the variable equal to the input that the user enters will make that variable (parameter) equal to the users input. – Simeon Ikudabo Mar 10 '18 at 22:57
  • You can dynamically create/destroy variables using the `dict` returned by `globals()`. But this should make you wonder, **why aren't you just using your own `dict`**? – juanpa.arrivillaga Mar 10 '18 at 23:01
  • Thanks everyone who replied. I see the advantage to using dicts here and will expand my usage of them. – Johan Mar 11 '18 at 23:59

0 Answers0