学习类的实例化的时候遇到了AttributeError: 'str' object has no attribute 'input_text', 以下是报错的代码及修改正确的代码。
class shuru_1: def __init__(self, input_text): self.input_text = input_text def repeat_input(self): print("输入的内容是:{}".format(self.input_text)) def main(): input_text = input("请输入一个数字:") shuru_1.repeat_input(input_text) if __name__ == '__main__': main()
输出结果:
请输入一个数字:1
Traceback (most recent call last):
File "D:/PythonProject/20180928/test.py", line 17, in <module>
main()
File "D:/PythonProject/20180928/test.py", line 14, in main
shuru_1.repeat_input(input_text)
File "D:/PythonProject/20180928/test.py", line 7, in repeat_input
print("输入的内容是:{}".format(self.input_text))
AttributeError: 'str' object has no attribute 'input_text'
代码修改:
class shuru_1: def __init__(self, input_text): self.input_text = input_text def repeat_input(self): print("输入的内容是:{}".format(self.input_text)) def main(): input_text = input("请输入一个数字:") Shuru_1 = shuru_1(input_text) Shuru_1.repeat_input() if __name__ == '__main__': main()
输出结果:
请输入一个数字:1
输入的内容是:1