如何导入外部类并在Python中创建一个对象?

时间:2013-11-26 21:32:08

标签: python

我用Google搜索过,我似乎无法找到一个明确的例子。我为Job类创建了一个名为job.py的文件。

class Job(object):
    title = ""
    pay = ""
    description = ""

    def __init__(self, title, pay, description):
        self.title = title
        self.pay = pay
        self.description = description

    def getNoobiness(self):
        return self.title

但是当我在同一目录中的测试文件中尝试这个时:

import job

job = Job("Fun Job", "7 elephants", "You will have much fun")

我收到此错误:

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    job = Job("Fun Job", "7 elephants", "You will have much fun")
NameError: name 'Job' is not defined

2 个答案:

答案 0 :(得分:4)

您需要从文件中导入该类:

from job import Job

如果您想保留当前导入,请执行此操作:

job.Job(...)

答案 1 :(得分:3)

您正在导入包含班级job的模块Job。但是,Python并不知道这一点;截至目前,它不知道Job在哪里。

要解决此问题,请将Job放在前面,明确告诉Python job.

import job
new_job = job.Job("Fun Job", "7 elephants", "You will have much fun")

现在,Python知道您正在使用Job模块中的job类。


或者,更简洁的解决方案是明确导入Job

from job import Job
job = Job("Fun Job", "7 elephants", "You will have much fun")