0

我的代码似乎不起作用,我正在尝试获取工作、类别和薪水的输入,并存储输入

class Jobs:

    def GetJob(self):
        name = raw_input('Enter a Job Title: ')
        category = raw_input('Enter what Category that Job is: ')
        salary = raw_input('Enter the salary of that Job: ')
        print name,category, salary

    def __init__(self,name,category,salary):
        self.name = Jobs.GetJob(name)
        self.category = Jobs.GetJob(category)
        self.salary = Jobs.GetJob(salary)


GetJob = Jobs()

print GetJob
4

1 回答 1

2

您的代码完全没有良好的 OOP 实践,第一部分 eandersson 的回答也是……</p>

一个类具有存储值、获取/设置它们并将转换返回(或应用)到其封装值的角色。你试图实现的完全是一派胡言:你GetJob在另一个方法中调用 Jobs 类的方法。如果你写的话,它可能会起作用:

def __init__(self,name…):
    self.name = Jobs.GetJob(self, name)
    …

但这将是设计程序的错误方法。你最好坚持你的班级来保持你的价值观并使它擅长这一点,并制作另一个有助于填充你的班级的功能:

class Jobs:   
    def __init__(self, name, category, salary):
        self.name = name
        self.category = category
        self.salary = salary

    def __repr__(self):
        return "Jobs<%s,%s,%s>" % (self.name, self.category, self.salary)

def GetJob():
    name = raw_input('Enter a Job Title: ')
    category = raw_input('Enter what Category that Job is: ')
    salary = raw_input('Enter the salary of that Job: ')
    return Jobs(name, category, salary)

print GetJob()

我不同意 eandersson 的方法,因为它通过直接调用 GetJob 方法欺骗了构造函数的目的。那么GetJob就没有用了。并且希望能够使用 Job 类,而不必总是在构建时使用原始输入。编辑:仅作为对他答案第一部分的评论有效。

最后,我认为你真的对编程有很多误解。您最好彻底阅读http://wiki.python.org/moin/BeginnersGuide/NonProgrammers上的 Python 课程,因为您确实忽略了很多概念来编写类似的东西。

去看看:

于 2013-05-05T15:15:31.197 回答