在多个实例中检查一些属性值,并在Python中从同一实例打印另一个属性



要详细解释,我有一些有关多个工作站的信息。例如,我有100个工作站,其名称,安装应用程序,用户和部门。

我想通过多个实例检查特定属性,并从同一实例打印另一个属性。例如,

我正在搜索用户" xxxx",如果存在打印另一个属性,例如机器名称或部门的" xxxx"用户属于。

我试图做到这一点,并且能够进行一个实例,就像在需要检查的对象中一样,我们可以使用类别的条件来提及。

但是,当我们有多个实例并随机检查特定属性是一个挑战。我试图找到一些提示,但没有成功。我是Python的初学者,如果有人可以回答,将会有所帮助。

from itertools import count
class Workstation(object):
"""Creates an workstation list-object"""
count = 0
    def __init__(self, machine_name, graphics, cad, user, dept):
        self.machine_name = machine_name
        self.graphics = graphics
        self.cad = cad
        self.user = user
        self.dept = dept
        Workstation.count += 1
    def ws_list(self):
        """showing the machine name with department"""
        print ('Name:', self.machine_name, 'Department:',  self.dept)

    def total(self):
        print ('the total count is %d' %Workstation.count)

    def info(self):
        print("enter the machine name")
        dept = raw_input(" ")
        if dept == self.dept:
            print ("the department is", self.machine_name)
        else:
            print ("the machine is not in the list")   

ws1 = Workstation("xxx", "nVidia Quadro FX 880M", "cad", 123, "IN")
ws2 = Workstation("yyy", "nVidia Quadro FX 880M", "cae", 456, "US")
ws3 = Workstation("zzz", "nVidia Quadro FX 880M", "IT", 789, "GE")
print ws1.machine_name
print ws1.ws_list()
print total

问:

jay

Workstation类不应该知道有多个实例。为此使用列表。这是一个使用简单列表和过滤器的示例:

class Workstation(object): 
    """Creates an workstation list-object"""
    def __init__(self, machine_name, graphics, cad, user, dept):
        self.machine_name = machine_name 
        self.graphics = graphics 
        self.cad = cad 
        self.user = user 
        self.dept = dept
# this is your database, containing all workstations
all_ws = [
    Workstation("xxx", "nVidia Quadro FX 880M", "cad", 123, "IN"),
    Workstation("yyy", "nVidia Quadro FX 880M", "cae", 456, "US"),
    Workstation("zzz", "nVidia Quadro FX 880M", "IT", 789, "GE") 
]
def filter_by_dept(workstations, dept):
    """Filters workstations by Department"""
    # the filtered list is created using a list comprehension
    return [x for x in workstations if x.dept == dept]
print("enter the department name") 
dept = raw_input(" ")
matching_ws = filter_by_dept(all_ws, dept)
for ws in matching_ws:
    # a more portable syntax for string formating
    print('Name: {} Department: {}'.format(self.machine_name, self.dept))
# the len() fonction returns the number of items in the list
print(len(matching_ws))

在此示例中,Workstation类仅具有属性(无方法)。您也可以简单地将这些属性存储在dict中,而不是使用自定义类。

最新更新