I have two files, one of the test.py is
import new.py
class Test:
def __init__(self):
return
def run(self):
return 1
if __name__ == "__main__":
one=Test()
one.run()
and new.py
class New:
def __init__(self):
one.run()
New()
Now when i run python test.py I get this error,
Traceback (most recent call last):
File "test.py", line 1, in <module>
import new.py
File "/home/phanindra/Desktop/new.py", line 5, in <module>
New()
File "/home/phanindra/Desktop/new.py", line 3, in __init__
one.run()
NameError: global name 'one' is not defined
But I want to use this instance of one in my New!!
Can I do this??
edit:
I want to access the variable in test.py in new.py to do some process and give them back to test.py. Isn't this possible?
If you want your New class to use the instance of Test you created, you have to pass it in as part of the constructor.
new.py
class New:
def __init__(self, one):
one.run()
test.py
import new
class Test:
def __init__(self):
return
def run(self):
return 1
if __name__ == "__main__":
one=Test()
two = new.New(one);
Playing around with globals is a great way to break your code without realizing how you did it. It is better to explicitly pass in the reference you want to use.
No, you can't. The closest you can get is to pass the thing you need in to the constructor:
class New(object):
def __init__(self, one):
one.run()
one is defined inside the if __name__=='__main__' block.
Consequently, one will get defined only if test.py is run as a script (rather than imported).
For the module new to access one from the test module, you'll need to pull one out of the if __name__ block:
test.py:
class Test:
def __init__(self):
return
def run(self):
return 1
one=Test()
if __name__ == "__main__":
one.run()
Then access one by the qualified name test.one:
new.py:
import test
class New:
def __init__(self):
test.one.run()
New()
Related
I have these two files:
main.py
def func_a():
return object_a.method()
class ClassA:
def __init__(self):
pass
def method(self):
return "k"
if __name__ == '__main__':
object_a = ClassA()
print(func_a())
import file_1
and file_1.py
import main
print(main.func_a())
I get these errors:
Traceback (most recent call last):
File "C:\Users\Utente\PycharmProjects\pythonProject\main.py", line 16, in <module>
import file_1
File "C:\Users\Utente\PycharmProjects\pythonProject\file_1.py", line 4, in <module>
print(main.func_a())
File "C:\Users\Utente\PycharmProjects\pythonProject\main.py", line 2, in func_a
return object_a.method()
NameError: name 'object_a' is not defined.
I would like to create object_a once by starting main.py, and have the object_a methods used by calling func_a from other files (which will be executed by main.py)
since __name__ != "__main__", object_a is never created in main.py. If you remove object_a = ClassA() from the if then it will run fine.
It is confusing, because you are expecting that having run the line: object_a = ClassA() that object_a will be attached to the main module.
You could try adding this as your first line of main.py:
print('top of main', __name__)
You will see this line execute twice as you are expecting, but with different outcomes.
What you should actually do to get what you want is to strip almost everything out of main.py except this:
if __name__ == '__main__':
object_a = ClassA()
print(func_a())
import file_1
plus enough imports to make this bit work, plus this: set_object_a(object_a)
Thus main.py can become:
if __name__ == '__main__':
set_object_a(ClassA())
print(func_a())
import file_1
Now everything else you had needs to go in another module all by itself like this:
# notmain.py
object_a = None
def set_object_a(a):
global object_a
object_a = a
def func_a():
return object_a.method()
class ClassA:
def __init__(self):
pass
def method(self):
return "k"
Now you can have any other modules do this and similar:
import notmain
print(notmain.func_a())
When I compile I get this error:
Traceback (most recent call last):
File "c:/Users/dvdpd/Desktop/ProjectStage/Main.py", line 1, in <module>
class Main:
File "c:/Users/dvdpd/Desktop/ProjectStage/Main.py", line 6, in Main
test = Reading()
NameError: name 'Reading' is not defined
Code:
class Main:
print("Welcome.\n\n")
test = Reading()
print(test.openFile)
class Reading:
def __init__(self):
pass
def openFile(self):
f = open('c:/Users/dvdpd/Desktop/Example.txt')
print(f.readline())
f.close()
I can't use the class Reading and I don't know why.
Main and Reading are in the same file so I think I don't need an import.
Forward declaration doesn't work in Python. So you'll get an error only if you create an object of the Main class as follows:
class Main:
def __init__(self):
print("Welcome.\n\n")
test = Reading()
print(test.openFile)
# Main() # This will NOT work
class Reading:
def __init__(self):
pass
def openFile(self):
f = open('c:/Users/dvdpd/Desktop/Example.txt')
print(f.readline())
f.close()
# Main() # This WILL work
Python source files are interpreted top to bottom by the interpreter.
So, when you call Reading() inside class Main, it does not exist yet. You need to swap the declarations to put Reading before Main.
You need to define Reading before Main
You need to define class Reading before class Main.
class Reading:
def __init__(self):
pass
def openFile(self):
f = open('c:/Users/dvdpd/Desktop/Example.txt')
print(f.readline())
f.close()
class Main:
print("Welcome.\n\n")
test = Reading()
print(test.openFile())
I have threading class in serverThread.py file as shown:
import threading
class serverThread(threading.Thread):
def __init__(self, name):
try:
threading.Thread.__init__(self)
self.name = name
except:
exit()
def run(self):
print("Hello")
I created a new project.I want to inherit class from above class as shown:
import serverThread
class tcpThread(serverThread):
def __init__(self, name):
serverThread.__init__(self,name)
def run():
serverThread.run(self)
t1 = tcpThread("Tcp Server")
t1.start()
When I run this script gives me error:
Error:
Traceback (most recent call last): File "serverTcpThread.py", line 4, in <module> class tcpThread(serverThread): TypeError: module.__init__() takes at most 2 arguments (3 given)
The error you're reporting is probably because the base class is imported from a bad path, cannot reproduce here.
That said, there's another (similar) error: when redefining the run method, you have to pass the self parameter
class tcpThread(serverThread):
def __init__(self, name):
serverThread.__init__(self,name)
def run(self):
serverThread.run(self)
the code runs fine after that. note that there's no need to redefine the run method only to call the parent method.
I am implementing my first class in Python and am struggling to make it work. I started with a very simple example:
#!/usr/bin/env python
"""
"""
import fetcher as fetcher
import fetchQueue as fetchQueue
def __init__(self, seed = "a string"):
self.seed = seed
myFetchQueue = fetchQueue.FETCHQueue()
def test(self):
print "test"
myFetchQueue.push(seed)
myFetchQueue.pop()
#Entrance of this script, just like the "main()" function in C.
if __name__ == "__main__":
import sys
myGraphBuilder = GRAPHBuilder()
myGraphBuilder.test()
and this class should call a method of another class I defined in a very similar way.
#!/usr/bin/env python
"""
"""
from collections import defaultdict
from Queue import Queue
class FETCHQueue():
linkQueue = Queue(maxsize=0)
visitedLinkDictionary = defaultdict(int)
#Push a list of links in the QUEUE
def push( linkList ):
print linkList
#Pop the next link to be fetched
def pop():
print "pop"
However when I run the code I get this output:
test Traceback (most recent call last): File "buildWebGraph.py", line 40, in <module>
myGraphBuilder.test() File "buildWebGraph.py", line 32, in test
myFetchQueue.push(seed) NameError: global name 'myFetchQueue' is not defined
So I guess that the construction of the object of class GRAPHBuilder and FETCHQueue is working, otherwise I would get an error before the string test gets outputed, but something else is going wrong. Can you help me?
def __init__(self, seed = "a string"):
self.seed = seed
myFetchQueue = fetchQueue.FETCHQueue()
Here, myFetchQueue is a local variable to the __init__ function. So, it will not available to other functions in the class. You might want to add it to the current instance, like this
self.myFetchQueue = fetchQueue.FETCHQueue()
Same way, when you are accessing it, you have to access it with the corresponding instance, like this
self.myFetchQueue.push(self.seed)
self.myFetchQueue.pop()
I am trying to learn python i tried to import a class in another class but it is not working
Application.py:
class Application:
def example(self):
return "i am from Application class"
Main.py
class Main:
def main():
application = Application()
application.example()
if __name__ == "__main__":
Main.main()
This gives me :
File "Main.py", line 11, in <module>
Main.main()
TypeError: unbound method main() must be called with Main instance as first argument (got nothing instead)
The error has nothing to do with importing (Although you don't seem to import Application anywhere). The problem is that you use the main method like a static method without declaring it to be static.
To solve this, You either need to declare your main method as static or create an instance of the Main class.
As a static method (add the #staticmethod decorator):
class Main():
#staticmethod
def main():
...
With an Instance:
class Main():
def main(self):
....
if __name__ == "__main__":
myMain = Main() #create an instance
myMain.main() #call the function on the instance
Also, to import your Application class from Application.py, you would just write this:
from Application import Application
You should instantiate your Main class first.
if __name__ == '__main__':
myMain = Main()
myMain.main()
But this will give you another error:
TypeError: main() takes no arguments (1 given)
There are two ways to fix this. Either make Main.main take one argument:
class Main:
def main(self):
application = Application()
application.example()
or make Main.main a static method. In which case you don't have to instantiate your Main class:
class Main:
#staticmethod
def main():
application = Application()
application.example()
if __name__ == "__main__":
Main.main()