代码之家  ›  专栏  ›  技术社区  ›  IliasP

初级Python类-使用用户输入更改属性值

  •  2
  • IliasP  · 技术社区  · 9 年前

    我只是在学习Python的课程,在过去的一天里,我一直在学习下面的内容。

    我试图使用用户输入(来自main()函数)来更改类中属性的值。

    我已经浏览了@property和@name。setter方法,允许您更改私有属性的值。

    然而,我试图找出如何使用用户输入更改非私有属性的值。

    我想出了下面的办法,但似乎行不通。运行程序后,属性的值保持不变。你知道为什么吗?

        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()
    
    3 回复  |  直到 9 年前
        1
  •  4
  •   TimK    9 年前

    在里面 choiceimpl 您正在使用 == 您应该使用的位置 = .

        2
  •  0
  •   L.S.    9 年前

    如前所述,您使用的是与==的比较,而不是=。 你也在回归自我。选择userinput作为返回值,但不要使用它,因为您设置了self。选择等于输入。

    较短的示例:

    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()
    
        3
  •  0
  •   iFala    9 年前

    1) 将:“==”(比较运算符)更改为“=”(分配)

    2) 班级内部: def choiceimpl(self,userInp): self.loud = self.userInp

    3) 课外活动

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