Python - итерация по классу - PullRequest
       16

Python - итерация по классу

0 голосов
/ 25 февраля 2012

Привет. Я пытаюсь написать метод, который выводит список местоположений сотрудников, которые сообщают менеджеру.Объект менеджера создан и содержит список ldaps (идентификаторов) для людей, которые отчитываются перед менеджером.

Как перебрать все объекты сотрудников - в данном случае 3 сотрудника, которые были созданы?Метод 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'])

Ответы [ 5 ]

2 голосов
/ 25 февраля 2012

Почему бы не заменить

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

на

manager1 = Manager('wayneg', 'Wayne Gretzky', 'Dublin', 50000, 'active', [employee1, employee2, employee3])

А затем просто:

def GetLocations(self):
    for emp in self.reportees:
        print emp.location
1 голос
/ 25 февраля 2012

Я бы добавил статический список местоположений в класс 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
1 голос
/ 25 февраля 2012

Это:

for location in [Employee]:
  print Employee.location

не имеет смысла. Вы создаете список [Employee], который содержит не сотрудника, а сам класс Employee. Вы хотите что-то вроде

for employee in self.reportees:
    print employee.location

но на самом деле вы не передаете свой экземпляр 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

даст вам то, что вы хотите. * * 1010

0 голосов
/ 25 февраля 2012
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.'

  # loop through that list of employees and print their locations
  def GetLocations(self):
    for employee in self.reportees:
      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')

# pass the employees to the manger
manager1 = Manager('wayneg', 'Wayne Gretzky', 'Dublin', 50000, 'active', [employee1,employee2, employee3])
0 голосов
/ 25 февраля 2012

Полный пример:

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

  def addReportee(self, reportee):
    self.reportees.append(reportee)

  def GetLocations(self):
    for reportee in self.reportees:
      print reportee.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', [employee1, employee2, employee3])
# and if you wanted to add more:
#manager1.addReportee(employee4)
#manager1.addReportee(employee5)
#manager1.addReportee(employee6)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...