初学者 Python 类 - 使用用户输入更改属性值
Beginner Python Classes - changing the attribute value with user input
我刚刚在 Python 中学习 classes,在过去的一天里,我一直坚持以下内容。
我正在尝试使用用户输入(来自 main() 函数)来更改 class 中的属性值。
我已经了解了允许您更改私有属性值的@属性 和@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()
在 choiceimpl
中你使用了 ==
而你应该使用 =
.
如前所述,您正在使用 == 而不是 = 进行比较。
此外,您在用户输入中 returning self.choice 作为 return 值,但永远不要使用它,因为您将 self.choice 设置为等于输入。
较短的示例:
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()
1) 更改:'=='(比较运算符)为'='(赋值)
2) 内部 class:
def choiceimpl(self,userInp):
self.loud = self.userInp
3) 外面 class
personA = Person(loud) # Create object
userInp = raw_input("Choose what you want: ") # Get user input
personA.choiceimpl(userInp) # Call object method
我刚刚在 Python 中学习 classes,在过去的一天里,我一直坚持以下内容。
我正在尝试使用用户输入(来自 main() 函数)来更改 class 中的属性值。
我已经了解了允许您更改私有属性值的@属性 和@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()
在 choiceimpl
中你使用了 ==
而你应该使用 =
.
如前所述,您正在使用 == 而不是 = 进行比较。 此外,您在用户输入中 returning self.choice 作为 return 值,但永远不要使用它,因为您将 self.choice 设置为等于输入。
较短的示例:
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()
1) 更改:'=='(比较运算符)为'='(赋值)
2) 内部 class:
def choiceimpl(self,userInp):
self.loud = self.userInp
3) 外面 class
personA = Person(loud) # Create object
userInp = raw_input("Choose what you want: ") # Get user input
personA.choiceimpl(userInp) # Call object method