2

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()
2
  • Hi @IliasP, have you thought of using raw_input() instead of output? Commented Feb 8, 2016 at 15:43
  • 1
    Hi @AndyK - thanks for the quick reply. Actually I did what TimK suggested below and it is working perfectly. Thanks again. Commented Feb 8, 2016 at 15:52

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks TimK. It is working now. That was really silly - sorry!
0

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()

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.