题解 | #修改属性1#
class Employee(object): def __init__(self, name, salary) -> None: self._name = name self._salary = salary def printclass(self, age=None): try: if age == None: raise Exception self._age = age print(f"{self._name}'salary is {self._salary}, and his age is {self._age}") except Exception as err: print('Error! No age') name = input() salary = input() e = Employee(name=name, salary=salary) e.printclass() age = input() e.printclass(age=age)
按题目要求在printclass中使用try...except
上面代码是通过属性传参来创建属性,也可以通过setattr来创建属性
class Employee(object): def __init__(self, name, salary) -> None: self._name = name self._salary = salary def printclass(self): try: print(f"{self._name}'salary is {self._salary}, and his age is {self._age}") except Exception as err: print("Error! No age") name = input() salary = input() e = Employee(name=name, salary=salary) e.printclass() age = input() setattr(e, '_age', age) e.printclass()