Python遍历类

2024-10-06 12:30:59 发布

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

嗨,我正在尝试写一个方法,打印一个员工的位置列表,并向经理汇报。创建管理器对象,并保存向经理报告的人员的ldap(id)列表。在

我如何迭代所有的employee对象-在本例中是3个已创建的employee对象?下面的GetLocations方法只打印管理器的位置。任何帮助都将不胜感激。谢谢!在

我想要一个输出,上面写着:都柏林,都柏林纽约(格式无关)

class Employee(object):
  def __init__(self, ldap, name, location, salary, status):
    self.ldap = ldap
    self.name = name
    self.location = location
    self.salary = salary
    self.status = status

class Manager(Employee):
  def __init__(self, ldap, name, location, salary, status, reportees):
    self.name = name
    self.reportees = reportees
    self.location = location
    print 'Manager has been created.'


  def GetLocations(self):
    for location in [Employee]:
      print Employee.location

employee1 = Employee('axlr', 'Axl Rose', 'Dublin', 50000, 'active')
employee2 = Employee('slash', 'Slash', 'Dublin', 50000, 'active')
employee3 = Employee('peterp', 'Peter Pan', 'New York', 50000, 'active')
manager1 = Manager('wayneg', 'Wayne Gretzky', 'Dublin', 50000, 'active', ['axlr', 'slash', 'peterp'])

Tags: 对象方法nameself列表defstatusemployee
3条回答

为什么不换

manager1 = Manager('wayneg', 'Wayne Gretzky', 'Dublin', 50000, 'active', ['axlr', 'slash', 'peterp'])

^{pr2}$

然后只是:

def GetLocations(self):
    for emp in self.reportees:
        print emp.location

这个:

for location in [Employee]:
  print Employee.location

没道理。您正在生成一个列表[Employee],其中不包含Employee,而是Employee类本身。你想要的是

^{pr2}$

但实际上您并没有将任何连接传递给您的Manager实例与员工本身,而只是给它一个名称列表。也许是像

    def GetLocations(self):
        for employee in self.reportees:
            print employee.location

employees = [Employee('axlr', 'Axl Rose', 'Dublin', 50000, 'active'),
             Employee('slash', 'Slash', 'Dublin', 50000, 'active'),
             Employee('peterp', 'Peter Pan', 'New York', 50000, 'active')]

manager1 = Manager('wayneg', 'Wayne Gretzky', 'Dublin', 50000, 'active', employees)

>>> manager1.GetLocations()
Dublin
Dublin
New York

会给你你想要的。在

我将向Employee类添加一个静态位置列表:

class Employee(object):
  locations = []
  def __init__(self, ldap, name, location, salary, status):
    self.ldap = ldap
    self.name = name
    self.location = location
    self.locations.append(location)
    self.salary = salary
    self.status = status

employee1 = Employee('axlr', 'Axl Rose', 'Dublin', 50000, 'active')
employee2 = Employee('slash', 'Slash', 'Dublin', 50000, 'active')
employee3 = Employee('peterp', 'Peter Pan', 'New York', 50000, 'active')
print Employee.locations

相关问题 更多 >