[英]Calling a constructor from a different class python
In one python file titled overall model, I have defined a constructor. 在一个名为总体模型的python文件中,我定义了一个构造函数。 In the same folder as the first python file, I have another python file that calls the constructor.
在与第一个python文件相同的文件夹中,我还有另一个python文件,该文件调用构造函数。
File 1: 文件1:
class OverallModel:
__init__(self,file_name):
#uses the file_name to do a series of calculations and then prints a result
File 2: 档案2:
class Runner:
x = OverallModel("file_name")
However. 然而。 I am getting the message that OverallModel is an undefined name in file 2. Am I suppose to import file 1 or am I not properly calling the constructor?
我收到一条消息,指出TotalModel是文件2中的未定义名称。我是否应该导入文件1,或者我没有正确调用构造函数? Thank you very much for the help.
非常感谢你的帮助。
An import is indeed needed, and you also missed the def keyword in the constructor: 确实需要导入,并且您也错过了构造函数中的def关键字:
file1.py
class OverallModel:
def __init__(self,file_name):
print "hey"
file2.py
from file1 import OverallModel
x = OverallModel("file_name")
Result: 结果:
$ python file2.py
hey
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.