我尝试在python中向数组中添加对象,然后打印数组的内容

I'm trying to add objects to an array in python and then print the contents of the array

本问题已经有最佳答案,请猛点这里访问。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import employee
def main():
    print('This program will create employee objects and store their information')
    print()
    ledger = []
    numOfEmployees = int(input("Enter the number of employee's to enter:"))
    for count in range(numOfEmployees):
        name = input("Enter employee's name:")
        id_number = input("Enter employee's ID number:")
        department = input("Enter employee's department:")
        job_title = input("Enter employee's job title:")
        count = employee.Employee(name, id_number, department, job_title)
        ledger.append(count)
    print("This is the list of employee's:")
    for person in ledger:
        print(person)
main()

以下是我的员工模块。我知道在模块中制作分类账会更有意义,但在我尝试实现它之前,似乎我应该先找出一种更简单的方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Employee:
    def __init__(self, name, id_number, department, job_title):
        self.__name = name
        self.__id_number = id_number
        self.__department = department
        self.__job_title = job_title
    def set_name(self, name):
        self.__name = name
    def set_id_number(self, id_number):
        self.__id_number = id_number
    def set_department(self, department):
        self.__department = department
    def set_job_title(self, job_title):
        self.__job_title = job_title
    def get_name(self):
        return self.__name
    def get_id_number(self):
        return self.__id_number
    def get_department(self):
        return self.__department
    def get_job_title(self):
        return self.__job_title

以下是输出。

1
2
3
4
5
6
7
8
This program will create employee objects and store their information

Enter the number of employee's to enter: 1
Enter employee'
s name: adf
Enter employee's ID number: afd
Enter employee'
s department: asdf
Enter employee's job title: asdf
This is the list of employee'
s:

我希望它能打印出这些值,而不仅仅是它在内存中的位置…我该怎么做?


要打印对象,需要提供其字符串表示形式的定义。然后,您在__str__()覆盖中描述了:

例如,您的可能是:

1
2
3
4
class Employee
    ... # other functions
    def __str__(self):
        return"{}, {}, {}".format(self.__name, self.__id_number, self.__department)

显然,您可以决定根据需要格式化它。

另外,你也应该去看看@property的装饰师,这样你就不需要自己做装饰师和装饰师,但这不是你的问题。


为对象定义一个__str__方法。当对象在需要字符串的上下文(通常是print中)中使用时,python会自动调用此方法。

例如。:

1
2
3
class Employee:
    def __str__(self):
        return self.__name