Python stud对象AttributeError:无number_of_students属性问题求助
问题分析与解决:AttributeError异常处理
原代码
class stud: def __init__(self) : try: self.number_of_students = int(input("Enter number of students :\n")) except ValueError: print("Enter numerical value") finally: print(self.number_of_students) obj1=stud()
问题现象
输入数值时程序正常运行;输入非数值内容时,除输出Enter numerical value外,还会抛出如下AttributeError异常:
AttributeError : File "e:\Data\Programming\Python!!!\OOP\tempCodeRunnerFile.py", line 14, in <module> obj1=stud() ^^^^^^ File "e:\Data\Programming\Python!!!\OOP\tempCodeRunnerFile.py", line 9, in __init__ print(self.number_of_students) ^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'stud' object has no attribute 'number_of_students'
原因分析
self.number_of_students属性仅在try块执行成功(输入为有效数值)时才会被创建并赋值- 输入非数值触发ValueError后,except块仅执行打印提示,不会给对象绑定
number_of_students属性 - finally块是无论try/except是否执行成功都会强制运行的代码块,此时对象不存在
number_of_students属性,因此打印时抛出AttributeError
解决方案
方案1:提前初始化属性默认值
在try块之前先给属性赋默认值,确保无论是否触发异常,属性都存在:
class stud: def __init__(self): self.number_of_students = 0 # 初始化默认值 try: self.number_of_students = int(input("Enter number of students :\n")) except ValueError: print("Enter numerical value") finally: print(self.number_of_students) obj1=stud()
方案2:在finally块中检查属性是否存在
通过hasattr()函数判断属性是否存在,避免直接访问不存在的属性:
class stud: def __init__(self): try: self.number_of_students = int(input("Enter number of students :\n")) except ValueError: print("Enter numerical value") finally: if hasattr(self, 'number_of_students'): print(self.number_of_students) else: print("未输入有效数值") obj1=stud()
方案3:在except块中给属性赋值
异常触发时也给属性赋一个占位值(比如None),保证属性存在:
class stud: def __init__(self): try: self.number_of_students = int(input("Enter number of students :\n")) except ValueError: print("Enter numerical value") self.number_of_students = None # 异常时赋值为None finally: print(self.number_of_students) obj1=stud()
内容的提问来源于stack exchange,提问作者ZulQarnain
相关产品推荐
相关产品推荐

