Python: assign result / variable value of function to class

I made a simple test program to experiment using classes. It creates a "person" class that accepts name and age arguments. Now I am trying to create an interactive program that allows the user to manage a list of people such as register or address book. They can create a new person as shown in the function below.

def createnew():
    newname = input("What is their name?")
    newage = input("How old are they?")

    newperson = Person(newname, newage)


Of course the problem with the above is that it is assigning newname literally and not the string value "newname". So I tried

newperson.lower() = Person(newname, newage)
str(newperson) = Person(newname, newage)
newperson[0:] = Person(newname, newage)


but they all return an error, cannot assign a function call. My question is how to access the value of the newname variable and assign it to Person or any other class.

Note. I am n00b / newb, meaning I didn't come from another language and am following the book. Please explain all the answers if they are not ridiculously obvious.

Many thanks.

To make it a little clearer, I'm trying to make the user-entered value for the new person, the name of the object name (in my example, it's newperson)


Thanks for all the answers, I believe it is not a great idea to allow the user to set variable names so that I re-bind my code. I created a dictionary that, after the user created a new person, writes the data specified by the str class function to the key of the given name. While this means I cannot access the object later on because the newperson will be overwritten, it allows me to list people with a dataset that I would like to do in the first place, I just mistakenly thought it would be easier to set object name. Thanks again.


source to share

4 answers

If you understand correctly, you want to create an object Person

and then create a global variable with a name that is the name of the person.

This is bad.

What you really want is a way to store objects of people and then search them by their names. So, use a dictionary:

people = {}

def createnew():
    people[newname] = Person(newname, newage)


Then you can access the Person in the dictionary:

print(people['name of the person'])


(I am assuming you are using Python 3 as you are using input()

, not raw_input()

as in Python 2.x)

If you really have to create a new variable (which is bad since people's names are usually not valid Python identifiers), use the function globals()


>>> globals()['foo'] = 2
>>> foo


but I am including this for the sake of completeness. Don't use this!



Are you using Python 2 or Python 3? I am guessing that perhaps your book is written for Python 3 and you are using Python 2. I think your first program should work in Python 3, but in Python 2 the function input

probably does not do what you expect it to do , The function raw_input

will be better. Let me know which version of Python you are using and I will try to give you more specific help. You should see the version number when you start the Python interpreter or when running python -V

on the command line.

This version of your code should work in Python 2:

def createnew():
    newname = raw_input("What is their name?")
    newage = int(raw_input("How old are they?"))

    person = Person(newname, newage)


I changed input

to raw_input

. As voithos suggests below, I used the "int" function to convert the input (with a string) to an integer. I also changed the last line to store the Person instance in a new variable person

instead newname

, because it can be quite confusing to reuse the same variable for two different value types.

The reason is input

giving you amazing results, it becomes clear if you check the documentation for this function:

It reads the input and then tries to evaluate it as a Python expression! When you enter a name, you get an error because it is not a variable name. Since this is pretty amazing and not often what you actually want, they changed it in Python 3, but that means the books and tutorials for Python 2 and 3 should be different and might lead to some confusion.



I'm not really sure what the problem is, but the code you show has some inconsistencies.

  • newname

    is an object reference string

    , then bind that object reference Person

    on the last line. This is bad design because it confuses the reader. Better to name your object Person

    something else, eg newPerson = Person( ... )

  • newname.lower()

    calls a function lower()

    on an object newname

    - this will work if newname

    it still was string

    , but now this Person

    . Have you defined a member function def lower(self)

    in the class Person

    ? What does the class look like?
  • str(newname)

    is noop if newname

    still a string

    . If it is an object Person

    , you must define a member function def __str__(self)

    that returns a string representation of your Person


Overall I'm not sure what you really want, but the Person class might look like this:

class Person(object):
    def __init__(self):"What is their name? ").capitalize()
        self.age=int(raw_input("How old are they? "))

    def __str__(self):
        return "My name is %s and I'm %d years of age." % (
  , self.age)



print p


Sidenote: Possibly bad construction to use raw_input

internally __init__

, and a function __str__

might return better Person(name=%s, age=%d) % ...

, but then this is just an example of how it works.



All of these function calls return values ​​instead of variables, so they cannot be changed. Mathematically, it's like trying to say 2 = 7 + 4

. Since 2 is not a variable and cannot really be assigned / changed in this way, it doesn't make much sense, and a bad translator gives you a tragic plea for help. Variables, on the other hand, as you probably already know, can be assigned this way in a view x = 7 + 4

. Changing the value contained in variable x is fine because the variables contain values, but trying to change the value of another value is not possible.

What you need to do is find the variable you want to change, put it to the left of the equal sign, and put the value you want to assign to it on the right side. When you say Person(newname, newage)

, you are creating a value, in this case an object, that must be assigned to a variable so that it can be saved and used later, rather than just undone right away:

def createnew():
    newname = input("What is their name?") #remember to indent these if you want them 
    newage = input("How old are they?")    #to be part of the function!
    newPerson = Person(newname, newage) 
    return newPerson


Now that newPerson

contains the value of the person you created, you can access the variables inside it and assign their values ​​just like any other. To do this, you need to know the names of the variables used, which are defined in the constructor you write, which probably looks something like this:

class Person:
    def __init__(self, name, age): = name      #the variable that contains the person name is called 'name'
        self.age = age       #the variable that contains the person age is called 'age'

def createnew():
    newname = input("What is their name?") #remember to indent these if you want them 
    newage = input("How old are they?")    #to be part of the function!
    newPerson = Person(newname, newage) 
    return newPerson

newperson = createnew() #will prompt you to enter name and age for this person and assign them

print( "person old name: " + ) = input("What is their new name?") #second thought, you want to change Bob name
print( "person new name: " + )




All Articles