繁体   English   中英

从其他类python调用构造函数

[英]Calling a constructor from a different class python

在一个名为总体模型的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")

然而。 我收到一条消息,指出TotalModel是文件2中的未定义名称。我是否应该导入文件1,或者我没有正确调用构造函数? 非常感谢你的帮助。

确实需要导入,并且您也错过了构造函数中的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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM