我有以下代码:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys import re
companies = {}
for line in open('/home/ibrahim/Desktop/Test.list'):
company, founding_year, number_of_employee = line.split(',')
number, name = company.split(")")
companies[name] = [name, founding_year, number_of_employee]
print "Company: %s" % company
CompanyIndex = raw_input('\n<Choose a company you want to know more about.>\n\n<Insert a companyspecific-number and press "Enter" .>\n')
if CompanyIndex in companies:
name, founding_year, number_of_employee = companies[CompanyIndex]
print 'The companys name is: ',name,'\nThe founding year is: ', founding_year,'\nThe amount of employees is: ', number_of_employee
else:
print"Your input is wrong."
该程序从如下所示的文本文件中读取一些信息:
(1)Chef,1956,10
(2)Fisher,1995,20
(3)Gardener,1998,50
我的目标是获得一个类,我可以在其中保存有关公司名称、成立年份和员 worker 数的信息,而不是使用还包含列表的字典。
我看了几个教程,但我真的不知道该怎么做。这个“ self ”是什么 __init__
和 __del__
做的等等,这真的很令人困惑。我该怎么做?
最佳答案
你可以这样做:
class Company(object):
def __init__(self, name, founding_year, number_of_employee):
self.name = name
self.founding_year = founding_year
self.number_of_employee = number_of_employee
之后,您可以通过编写 company = Company('Chef', 1956, 10)
创建一个 Company
对象。
关于python - 使用类而不是列表 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18743669/