列表

详情


NP98. 修改属性1

描述

请为牛客网的员工创建一个Employee类,包括属性有姓名(name)、(salary),并设置初始化。同时该类包括一个方法printclass,用于输出类似'NiuNiu‘s salary is 4000, and his age is 22'的语句。
请根据输入的name与salary为该类创建实例e,并调用printclass方法输出信息,如果没有年龄信息则输出错误信息"Error! No age"。
根据输入的年龄为实例e直接添加属性age等于输入值,再次调用printclass方法输出信息。(printclass方法中建议使用try...except...结构)

输入描述

三行分别输入姓名name、工资salary、年龄age,其中第一个为字符串,后两个为整型数字。

输出描述

根据描述输出错误信息或是打印信息。

示例1

输入:

NiuNiu
8000
22

输出:

Error! No age
NiuNiu'salary is 8000, and his age is 22

原站题解

Python 3 解法, 执行用时: 28ms, 内存消耗: 4424KB, 提交时间: 2022-08-03

print("""Error! No age
NiuMei'salary is 16000, and his age is 25""")

Python 3 解法, 执行用时: 28ms, 内存消耗: 4456KB, 提交时间: 2022-07-31

class Employee:
    def __init__(self,name,salary):
        self.n = name
        self.s = salary
    def printclass(self):
        try:
            print(f"{self.n}'salary is {self.s}, and his age is {self.age}")
        except:
            print("Error! No age")

e = Employee(input(),input())
e.printclass()
e.age = input()
e.printclass()

Python 3 解法, 执行用时: 28ms, 内存消耗: 4464KB, 提交时间: 2022-08-01

class Employee:
    def __init__(self,name,salary):
        self.name=name
        self.salary=salary
        
    def printclass(self):
        try:
            self.age=age
            print("{}'salary is {}, and his age is {}".format(self.name,self.salary,self.age))
        except:
            print('Error! No age')
name=input()
s=int(input())

e=Employee(name,s)
e.printclass()
age=int(input())
e.age=age
e.printclass()
    

Python 3 解法, 执行用时: 28ms, 内存消耗: 4468KB, 提交时间: 2022-07-28

class Employee():
    def __init__(self,name,salary):
        self.name = name
        self.salary = salary

        
    def printclass(self):
        try:
            print("%s'salary is %d, and his age is %s" % (self.name,self.salary,self.age))
        except:
            print("Error! No age")

name = input()
salary = int(input())
age = int(input())

e = Employee(name,salary)
e.printclass()
e.age = age
e.printclass()

Python 3 解法, 执行用时: 28ms, 内存消耗: 4472KB, 提交时间: 2022-08-06

name = input()
salary = int(input())

class Employee:
    def __init__(self,name,salary,age=None):
        self.name = name
        self.salary = salary
        self.age = age
    def printclass(self):
        try:
            if self.age == None:
                return "Error! No age"
            else:
                return f"{self.name}'salary is {self.salary}, and his age is {self.age}"
        except Exception as e:
            return e
e = Employee(name,salary)
print(e.printclass())
e.age = int(input())
print(e.printclass())

        
        
        
        
        

上一题