IliasP February 2016

Beginner Python Classes - changing the attribute value with user input

I am just learning classes in Python and for the past day I am stuck with the below.

I am trying to use a user input (from the main() function) to change the value of an attribute in the class.

I have been throught the @property and @name.setter methods that allow you to change the value of a private attribute.

However I am trying to find out how you can use user input to change the value of an attribute that is not private.

I came up with the below but it does not seem to work. The value of the attribute remains the same after I run the program. Would you have any ideas why?

    class Person(object):

    def __init__(self, loud, choice = ""):
        self.loud = loud
        self.choice = choice

    def userinput(self):
        self.choice = input("Choose what you want: ")
        return self.choice

    def choiceimpl(self):
        self.loud == self.choice

    def main():

        john = Person(loud = 100)

        while True:

            john.userinput()

            john.choiceimpl()

            print(john.choice)
            print(john.loud)

    main()

Answers


TimK February 2016

In choiceimpl you are using == where you should use =.


L.S. February 2016

Like stated before, you are using a comparison with == instead of the =. Also you are returning self.choice in userinput as a return value, but never use it, because you set self.choice equal to input.

Shorter example:

class Person:
    def __init__(self, loud):
        self.loud = loud
    def set_loud(self):
        self.loud = input("Choose what you want: ")
def main():
    john = Person(100)
    while True:
        john.set_loud()
        print(john.loud)
main()


iFala February 2016

1) Change: '=='(comparison operator) to '='(to assign)

2) Inside class: def choiceimpl(self,userInp): self.loud = self.userInp

3) Outside class

personA = Person(loud)                         # Create object
userInp = raw_input("Choose what you want: ")  # Get user input
personA.choiceimpl(userInp)                    # Call object method

Post Status

Asked in February 2016
Viewed 1,281 times
Voted 8
Answered 3 times

Search




Leave an answer