學習類的實例化的時候遇到了AttributeError: 'str' object has no attribute 'input_text', 以下是報錯的代碼及修改正確的代碼。 輸出結果: 請輸入一個數字:1Traceback (most recent call last): File "D:/ ...
學習類的實例化的時候遇到了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