簡體   English   中英

我如何獲取 class object 的數據,從他想查看的 object 的用戶那里獲取輸入?

[英]How can I get data for a class object, taking input from user of which object he would like to view?

首先,我創建了一個名為“employed”的 class,它看起來像這樣——

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}")

然后,我為這個類創建了兩個 class 對象-

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

現在我想從用戶那里獲取他喜歡查看哪個對象數據的輸入。 我怎樣才能做到這一點?

首先,我們定義了一個function,如果function返回none,則返回匹配該名稱的用戶,則表示不存在該名稱的用戶,否則返回用戶。 在此之前,為了方便起見,我已將所有用戶添加到列表中

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 中沒有開關盒,但您可以按如下方式實現它 在 class 中定義這些函數

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()
    

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM