Calling a constructor from a different class python - 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

Related

Using python function from other python file and subsequent class?

I have been learning working with classes in python after learning OOPs in c++.
I am working on a project, where I have a class defined in one file, and an important function to be used in the class in the seperate file.
I have to call the class in the first file, but I am getting the ImportError.
Great, if you could help.
try1.py
from try2 import prnt
class a:
def __init__(self):
print("started")
def func1(self):
print("func1")
prnt()
try2.py
from try1 import a
b = a()
b.func1()
def prnt():
b.func()
As for eg, in the above example, when I am running try1.py, I am getting an ImportError: cannot import name 'prnt'.
You absolutely need to redesign your project. Even if you did manage to get away with the cyclic imports (ie by moving the import to inside the function - but don't do it) you will still get a NameError: name 'b' is not defined since b is not define in prnt.
Unless prnt can't be defined in class a (why?), consider defining prnt in a third, "utils" file and import it in both try1.py and try2.py and pass an object to it so it can access all of its attributes.
Just run your code, read the error, and deduct something from it.
When you run it, here is the error message :
Traceback (most recent call last):
File "C:\Users\Kilian\Desktop\Code\Garbage\tmp.py", line 7, in <module>
from temp2 import prnt
File "C:\Users\Kilian\Desktop\Code\Garbage\temp2.py", line 1, in <module>
from tmp import a
File "C:\Users\Kilian\Desktop\Code\Garbage\tmp.py", line 7, in <module>
from temp2 import prnt
ImportError: cannot import name prnt
Your script is trying to import something it already has tried to import earlier on. Python is probably deducing that it can't import it. :)

how to import a python class's moudle?

I have this main.py, in it:
import uuid
class tools(object):
def generate_uuid(self):
return self.uuid.uuid4()
in my calling program callmain.py, I have
import main
result = main.tool.generate_uuid()
print ("result")
if I run my callmain.py: I get
"TypeError: generate_uuid() missing 1 required positional argument:
'self'
if I add self to the line
result = main.tool.generate_uuid(self): I get
NameError: name 'self' is not defined
How to fix this? thank for help.
because you should make a object from your class first. then call your sub function like this:
import main
result = tools()
result.generate_uuid()
print(result) # "result" is a string! you should just call result without any "".
If you want to use the module of a class you have to create an instance of that class first and call if from that instance, that way the self argument is passed a valid reference to an instance of that class. For example:
import main
tools_instance = main.tools()
result = tools_instance.generate_uuid()
The style of importing shown in your question looks like a package. In packages a folder of python files __init__.py can be arranged in a particular way, documented here Python Packages. An example from the docs
parent/
__init__.py
one/
__init__.py
two/
__init__.py
three/
__init__.py
So an package of the format
main/
__init__.py
tools/
__init__.py # Add function 'generate_uuid' in this file
Could be utilized as follow:
import main
result = main.tools.generate_uuid()
print(result)

How to access variable defined in constructor from another file in python

I have a python file file1 which has below code
Class myClass():
def __init__(self):
self._variable1 = 2
Now how can I access variable1 from another python file
from file1 import myClass
class = myClass()
class._variable1 ??
how can I access these variables.?
all done fine, except the name class for variable
try it
from file1 import myClass
cl = myClass()
cl.variable1
newer user python keywords as variable name, list of it you may look
import keyword
keyword.kwlist
more details lexical_analysis

How do you import files into the Python shell?

I made a sample file that uses a class called Names. It has its initialization function and a few methods. When I create an instance of the class it retrieves the instance's first name and last name. The other methods greet the instance and say a departure message. My question is: how do I import this file into the Python shell without having to run the module itself?
The name of my file is classNames.py and the location is C:\Users\Darian\Desktop\Python_Programs\Experimenting
Here is what my code looks like:
class Names(object):
#first function called when creating an instance of the class
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
#class method that greets the instance of the class.
def intro(self):
print "Hello {} {}!".format(self.first_name, self.last_name)
def departure(self):
print "Goodbye {} {}!".format(self.first_name, self.last_name)
But I get the error:
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
import classNames.py
ImportError: No module named classNames.py
I am not clear about what you expect and what you see instead, but the handling of your module works exactly like the math and any other modules:
You just import them. If this happens for the first time, the file is taken and executed. Everything what is left in its namespace after running it is available to you from outside.
If your code only contains just def, class statements and assignments, wou won't notice that anything happens, because, well, nothing "really" happens at this time. But you have the classes, functions and other names available for use.
However, if you have print statements at top level, you'll see that it is indeed executed.
If you have this file anywhere in your Python path (be it explicitly or because it is in the current working directory), you can use it like
import classNames
and use its contents such as
n = classNames.Names("John", "Doe")
or you do
from classNames import Names
n = Names("John", "Doe")
Don't do import classNames.py, as this would try to import module py.py from the package classNames/.

Multiple modules , single instance of a class - Python

I have two modules misc.py and main.py and would like to define all classes present in misc.py in main.py.
Below is the code
#misc.py
class dummy:
def __init__(self):
pass
def dummyPrint(self):
print "Welcome to python"
#main.py
import misc
dummyObj = dummy()
dummyObj.dummyPrint()
Is this the right way to go ? I do not see any output i.e., Welcome to python
$python misc_main.py misc.py
EDIT: I added the statement from misc import dummy and i am getting the following error
$python misc_main.py main.py
Traceback (most recent call last):
File "misc_main.py", line 5, in <module>
dummyObj = dummmy()
NameError: name 'dummmy' is not defined
When you do the following command, you are calling misc_main.py from the interpreter with misc.py as an argument.
python misc_main.py misc.py
Since misc_main is not reading command line arguments, this is equivalent to
python misc_main.py
I am surprised that you do not get errors, in either case. You need to import the actual class if you want to get output.
from misc import dummy
dummyObj = dummy()
dummyObj.dummyPrint()
Note, I am assuming your main file is actually in called misc_main.py rather than main.py as you have stated in your question. Otherwise you are not invoking the correct file.

Categories

Resources