简体   繁体   中英

Calling a constructor from a different class python

In one python file titled overall model, I have defined a constructor. In the same folder as the first python file, I have another python file that calls the constructor.

File 1:

class OverallModel:

    __init__(self,file_name):

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

File 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? Thank you very much for the help.

An import is indeed needed, and you also missed the def keyword in the constructor:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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