从另一个类python调用构造函数

时间:2017-07-27 18:45:11

标签: python constructor

在一个标题为整体模型的python文件中,我定义了一个构造函数。在与第一个python文件相同的文件夹中,我有另一个调用构造函数的python文件。

文件1:

class OverallModel:

    __init__(self,file_name):

        #uses the file_name to do a series of calculations and then prints a result

文件2:

class Runner:

    x = OverallModel("file_name")

然而。我收到的消息是,OverallModel是文件2中未定义的名称。我是想导入文件1还是我没有正确调用构造函数?非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

确实需要导入,并且您还错过了构造函数中的def关键字:

file1.py

class OverallModel:

    def __init__(self,file_name):
        print "hey"

file2.py

from file1 import OverallModel

x = OverallModel("file_name")

结果:

$ python file2.py
hey