如何从用户希望查看的对象中获取类对象的数据?

2024-04-24 07:42:53 发布

您现在位置:Python中文网/ 问答频道 /正文

首先,我创建了一个名为“employed”的类,它看起来像这样-

class employed:
    def __init__(self,name, age, salary, role):
        self.name = name ; self.age = age
        self.salary = salary ; self.role = role

    def givedata(self):
        return(f"name : {self.name}\nage : {self.age}\nsalary : {self.salary}\nrole : {self.role}")

然后,我为这个类创建了两个类对象-

saksham = employed("Saksham", 13, 10000, "developer")
rohan = employed("Rohan", 15, 12000, "team leader")

现在我想从用户那里获取他想要查看的对象数据的输入。我该怎么做


2条回答

首先,我们定义了一个函数,返回与名称匹配的用户 如果函数返回none,则表示没有该名称的用户,否则将返回user。 在此之前,为了方便起见,我已将所有用户添加到列表中

saksham = employed("Saksham", 13, 10000, "developer")
rohan = employed("Rohan", 15, 12000, "team leader")
objects = []
objects.append(saksham)
objects.append(rohan)

def view_object(name):
 for user in objects:
  if user.name == name:
   return user;


name = input("Hey User... Who do you want to view: "

user = view_object(name)
if user is None:
 print("Sorry there is no user with this name")
else:
 print(str(user))

python中没有开关的情况,但您可以按如下方式实现它 在类中定义这些函数

def get_name(self):
    return self.name     
def get_salary(self):
    return self.salary

然后使用以下方法

def numbers_to_months(argument):
    switcher = {
        1: object.get_salary(),
        2: object.get_name(),
    }

    # Get the function from switcher dictionary
    func = switcher.get(argument, lambda: "Invalid month")
    # Execute the function
    print get_salary()
    

相关问题 更多 >