列表

详情


NP99. 修改属性2

描述

请为牛客网的员工创建一个Employee类,包括属性有姓名(name)、(salary),并设置初始化。同时该类包括一个方法printclass,用于输出类似'NiuNiu‘s salary is 4000, and his age is 22'的语句。
请根据输入的信息为Employee类创建一个实例e,调用hasattr方法检验实例有没有属性age,如果存在属性age直接调用printclass输出,否则使用setattr函数为其添加属性age,并设置值为输入后,再调用printclass输出。

输入描述

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

输出描述

第一行输出e有没有属性age,True或者False;
第二行输出printclass打印信息。

示例1

输入:

NiuNiu
4000
23

输出:

False
NiuNiu'salary is 4000, and his age is 23

原站题解

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

na = input('')
sa = input()
ag = input()


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

    def printclass(self):
        if hasattr(Employee,'age') == 'True':
            print("{}'salary is {}, and his age is {}".format(self.name, self.salary, self.age))

        else:
            print('False')
            setattr(Employee,'age',ag)
            print("{}'salary is {}, and his age is {}".format(self.name, self.salary, self.age))

e = Employee(na, sa)

e.printclass()

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

class Employee:
    def __init__(self,name,salary):
        self.name = name
        self.salary = salary
     
    def printclass(self):
        print(f"{self.name}'salary is {self.salary}, and his age is {self.age}")
     
name = input()
salary = int(input())
age = int(input())
 
e = Employee(name,salary)
if not hasattr(e,"age"):
    print(False)
    e.age = age
    e.printclass()
else:
    print(True)

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

class Employee(object):
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary
        
    def printcalss(self):
        try:
            return (f'{self.name}\'salary is {self.salary}, and his age is {self.age}')
        except:
            return('Error! No age')
        
        
name, salary, age = input(), int(input()), int(input())
    
e = Employee(name, salary)
print(hasattr(e,'age'))

e.age = age
print(e.printcalss())

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

class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary
    def printclass(self):
        print(f"{self.name}'salary is {self.salary}, and his age is {self.age}")

name = input()
salary = int(input())
age = int(input())
 
e = Employee(name,salary)
if not hasattr(e,"age"):
    print(False)
    e.age = age
    e.printclass()
else:
    print(True)

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

class Employee():
    def __init__(self,name,salary):
        self.name=name
        self.salary=salary
    def printclass(self):
        print("{}'salary is {}, and his age is {}".format(self.name,self.salary,self.age))
name=input()
salary=int(input())
age=int(input())
e=Employee(name,salary)
if hasattr(e,'age'):
    print(True)
else:
    setattr(e,'age',age)
    print(False)
e.printclass()

上一题