Multiple modules , single instance of a class - Python - 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.

Related

How can I run a script after importing it?

Problem
I would like to import a script containing many functions and then run them, so that I can use the function. I may have misunderstood the purpose of import. I am working in Jupyter.
Reprex
#Create the script in a local folder
%%writefile test.py
c = 500
def addup(a,b,c):
return a*b + (c)
#import the file and use it
import test
addup(1,5,c)
#Error message
---------------------------------------------------------------------------
# NameError Traceback (most recent call last)
# <ipython-input-1-71cb0c70c39d> in <module>
# 1 import test
# ----> 2 addup(1,5,c)
# NameError: name 'addup' is not defined
Any help appreciated.
You have not called the function! You need a dot . to call a function from a module.
This is the correct syntax:
import test
result = test.addup(1,5,c)
Import a specific function:
from test import addup
addup(1,5,c)
Importing all of the module's functions:
from test import *
addup(1,5,c) # this way you can use any function from test.py without the need to put a dot

Simple case of __init__.py and import giving mysterious module not found

I've tried this from so many different angles but can't sort it out. Must be such a simple case. In Python 3.7.6:
Directory structure:
./modtest/
./modtest/__init__.py
./modtest/test1.py
./modtest/test2.py
test1.py:
import modtest
def x(i):
print(i)
y(i)
test2.py:
def y(i):
print(i)
__init__.py is an empty file.
When I attempt to run the code:
$ /Users/pitosalas/miniconda3/bin/python /Users/pitosalas/mydev/rsb_py/modtest/test1.py
Traceback (most recent call last):
File "/Users/pitosalas/mydev/rsb_py/modtest/test1.py", line 1, in <module>
import modtest
ModuleNotFoundError: No module named 'modtest
From what I read this should've worked. I'm sure there's something trivial wrong!
You are importing modtest in test1.py while this module itself resides inside of modtest. This can't be because modest wouldn't have yet been defined and added to the search path. So this is what you should have actually:
./modtest/
./modtest/__init__.py
./modtest/
./modtest/test2.py
./test1.py # this module must be outside of modtest

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. :)

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

Writing and importing custom modules/classes

I've got a class that I'm trying to write called dbObject and I'm trying to import it from a script in a different folder. My structure is as follows:
/var/www/html/py/testobj.py
/var/www/html/py/obj/dbObject.py
/var/www/html/py/obj/__init__.py
Now, __init__.py is an empty file. Here are the contents of dbObject.py:
class dbObject:
def __init__():
print "Constructor?"
def test():
print "Testing"
And here's the contents of testobj.py:
#!/usr/bin/python
import sys
sys.path.append("/var/www/html/py")
import obj.dbObject
db = dbObject()
When I run this, I get:
Traceback (most recent call last):
File "testobj.py", line 7, in <module>
db = dbObject()
NameError: name 'dbObject' is not defined
I'm new to Python, so I'm very confused as to what I'm doing wrong. Could someone please point me in the right direction?
EDIT: Thanks to Martijn Pieters' answer I modified my testobj.py as follows:
#!/usr/bin/python
import sys
sys.path.append("/var/www/html/py")
sys.path.append("/var/www/html/py/dev")
from obj.dbObject import dbObject
db = dbObject()
However, now when I run it I get this error:
Traceback (most recent call last):
File "testobj.py", line 7, in <module>
db = dbObject()
TypeError: __init__() takes no arguments (1 given)
Is this referring to my init.py or the constructor within dbObject?
EDIT(2): Solved that one myself, the constructor must be able to take at least one parameter - a reference to itself. Simple fix. Looks like this problem is solved!
EDIT (Final): This is nice - I can cut out the import sys and sys.path.append lines and it still works in this instance. Lovely.
You need to import the class from the module:
from obj.dbObject import dbObject
This adds the class dbObject directly to your local namespace.
Your statement import obj.dbObject adds the name obj to the local namespace, so you could also do this instead:
db = obj.dbObject.dbObject()
because obj.dbObject is the dbObject.py module in your obj package directory.

Categories

Resources