Search code examples
pythonclassdictionaryobjectuser-input

creating an object from user input


So I'm fairly new to python and I wanted to make a program that creates an object of a class from the user input, so I don´t have to make 10 empty profiles. I´ve tried it like this, knowing that it'll be false, but I think it demonstrates my problem.

class Profile():
    def __init__(self, weight, height):
        self.weight = weight
        self.height = height

def create_object():
    name = input("What's your name?")
    new_weight = input("What's your height?")
    new_height = input("What's your weight?")

    name = Profile(new_weight, new_height)
    return name

If i now want to create the object:

>>> create_object()
What's your name? test 
What's your height? 23 
What's your weight? 33
<__main__.Profile object at 0x000002564D7CFE80>

>>> test()
Traceback (most recent call last):
File "<pyshell#35>", line 1, in <module>
    test()
NameError: name 'test' is not defined

or should I use a dictonary and if yes, how?


Solution

  • In my experience, it is not necessary to specifically name each instance of a class. Instead, you could do as some commenters suggested and add each new object to a dictionary, like so:

    object_dict = {}
    for i in range(10):
        name = input("what's your name")
        object_dict[name] = create_object()
    

    The difference to note here is that I moved the name portion of your funtion to outside of the create_object() scope. To my knowledge, there are no "easy" or "clean" ways to create variables in python with a string as the user input (especially not if you are new to python).

    If what you are doing doesn't necessarily need the name, and the user details are only for data storage, then it would be more concise to save the name as a property in your class, like so:

    class Profile():
        def __init__(self, weight, height, name):
            self.weight = weight
            self.height = height
            self.name = name
    

    And then when you generate the profiles, simply add them to a list:

    for i in range(10):
        object_list.append(create_object())
    

    One last thing, the input method always returns a string. So if you plan to do math with the weight and height values, you will need to change the input from a string to a number, which you can do by surrounding the input() call with int() like

    weight = int(input("What's your weight?"))
    height = int(input("What's your height?"))