题解 | #修改属性1#
修改属性1
https://www.nowcoder.com/practice/c5ab441e5e8f4ec7bf36ba51a3141340
name = input()
salary = int(input())
age = int(input())
class Employee(object):
def __init__(self, name, salary):
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:
print("Error! No age")
e = Employee(name, salary)
e.printclass()
e.age = age
e.printclass()
记录几点:
- try...except... try跟的是“尝试执行的代码”,except跟的是“尝试失败出现错误的处理”。若try后代码可以执行,就跳过except;若try后代码不可执行,就执行完except再继续。
- 在类外给实例对象设置属性,虽简单但不推荐使用。 e.age = age
- 本题题目中的输出和示例中的输出不一致。注意!
