-3

我正在尝试制作一个程序,您可以输入职位名称、类别和薪酬,并且我正在尝试将输入的职位名称、类别和薪酬写入文件以存储数据,但我在这样做时遇到了问题。

class Job(object):
    def __init__(self, jobName = '', jobCategory = '', jobPay = ''):
        self.jobName = jobName
        self.jobCategory = jobCategory
        self.jobPay = jobPay

    def getName(self):
        self.jobName = input("What is the Job Title: ")

    def getCategory(self):
        self.jobCategory = input("What is the Job Category: ")

    def getPay(self):
        self.jobPay = input("What is the Job Pay: ")

    def displayJob(self):
        print("Job: " + self.jobName)
        print("Job Category: " + self.jobCategory)
        print("Job Pay: " + self.jobPay)
        print()


def Main():
    global NewJob
    NewJob = Job()
    NewJob.getName()
    NewJob.getCategory()
    NewJob.getPay()
    print()
    NewJob.displayJob()
    myFile = open('newFile.txt', 'w')
    myFile.write(NewJob.displayJob())
    myFile.close()

Main()
4

2 回答 2

2

displayJob()打印到标准输出,而不是您的文件。您必须返回一个字符串:

def displayJob(self):
    results = [
        "Job: " + self.jobName,
        "Job Category: " + self.jobCategory,
        "Job Pay: " + self.jobPay
    ]

    return "\n".join(results)

或者作为参数传递file,但这看起来有点奇怪:

import sys

def displayJob(self, file=sys.stdout):
    print("Job: " + self.jobName, file=file)
    print("Job Category: " + self.jobCategory, file=file)
    print("Job Pay: " + self.jobPay, file=file)
    print(file=file)

...

NewJob.displayJob(myFile)
于 2013-06-26T20:37:16.713 回答
0

假设问题是没有写入文件。 Job.displayJob()不返回要写入文件的任何内容,它仅将其显示到标准输出。弄清楚您希望您的对象如何序列化到文件并拥有一个返回该字符串的方法。

于 2013-06-26T20:36:13.370 回答