4

次のコードがあります。

#!/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

私の目的は、リストも含まれている辞書を使用する代わりに、会社名、創業年、および従業員数に関する情報を保存できるクラスを取得することです。

いくつかのチュートリアルを読みましたが、その方法が本当にわかりません。この「自己」とは何なのか、何をしているのかなど、本当に混乱__init____del__ました。どうすればこれを行うことができますか?

4

4 に答える 4

2

できるよ:

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 = Company('Chef', 1956, 10)

于 2013-09-11T14:21:38.857 に答える
1
class companies(object):
    def __init__(self,text_name):
        text_file = open(text_name,'r')
        companies = {}
        all_text = text_file.read()
        line = all_text.split('\n')  #line is a list
        for element in line:
            name,year,number = element.split(',')
            companies[name] = [year,number]
        self.companies = companies

    def get_information(self,index):
        print self.companies[index]

 #an instance of the class defined above
my_company = companies(r'company.txt')
 #call function of my_company
my_company.get_information(r'Gardener')
于 2013-09-11T15:50:48.570 に答える
1

CompanyInfoクラスを作成する方法の例を次に示します。

class CompanyInfo(object):
    def __init__(self, name, founded_yr, empl_count):
        self.name = name
        self.founded_yr = founded_yr
        self.empl_count = empl_count

    def __str__(self):
        return 'Name: {}, Founded: {}, Employee Count: {}'.format(self.name, self.founded_yr, self.empl_count)

作成方法の例を次に示します。

# ...
for line in open('/home/ibrahim/Desktop/Test.list'):
    company, founding_year, number_of_employee = line.split(',')
    comp_info = CompanyInfo(company, founding_year, number_of_employee)

そして、これはあなたがそれをどのように使用するかの例です:

print "The company's info is:", str(comp_info)
于 2013-09-11T14:29:54.337 に答える