0

I have a class file and a separate file containing main(). In the main() file, I'm trying to create 3 different employees, pass the info to the file with the class, and return it to the main() file with str.

The end of employee.py (file with the class):

def __str__(self):
    for num in range(3):
        return 'Employee ' + str(num+1) + ': ' + '\n' \
               + 'Name: ' + self.__name + '\n' \
               + 'ID Number: ' + str(self.__id_num) + '\n' \
               + 'Department: ' + self.__department + '\n' \
               + 'Job Title: ' + self.__job_title

The file that contains main():

import employee

def main():

    employ_list = [0] * 3

    for num in range(3):
        name = input('Enter the name for employee #' + str(num+1) + ': ')
        id_num = int(input('Enter the ID number for employee #' \
                       + str(num+1) + ': '))
        department = input('Enter the department for employee #' \
                       + str(num+1) + ': ')
        job_title = input('Enter the job title for employee #' \
                      + str(num+1) + ': ')
        print()

        employ_list[num] = [employee.Employee(name, id_num, department, job_title)]

    print(employ_list)

What I'm expecting to be returned and displayed is

Employee 1:
Name: Mary Smith
ID number: 123456
Department: Accounting
Title: Accountant

(just with 3 people)

but when I run the program, all I get is this:

[[<employee.Employee object at 0x06339E70>], [<employee.Employee object at 0x06339EF0>], [<employee.Employee object at 0x06339F70>]]

I'm pretty new to python and programming in general so any help would be appreciated.

lii3cu
  • 1
  • Put simply, when Python is converting the list `employ_list` to a string to print it, is calls `str` on the top-level `list` object, but `__repr__` for the elements contained _within_ the list object itself. Thus, you also need to overload the `__repr__` method for the `Employee` class. This can be done simply by re-using your implementation of the `__str__` method. In other words, put `__repr__ = __str__` in the `Employee` class definition. – Christian Dean May 07 '18 at 18:25
  • @ChristianDean Thanks for your comment! Sorry that you took time out of your day to answer a duplicate question but I had seen the other post about the "confusion with `__str__`." I just asked a new question because I was confused with what was being said in the that post and thought they were saying to change `__str__` to `__repr__` (I needed to use `__str__` for this assignment). And maybe they were saying to change it, I'm still a little confused. But I ended up tweaking some of the code in main() where instead of `print(employee_list)`, I used a loop to print each employee separate. – lii3cu May 08 '18 at 18:01

0 Answers0