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())
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())
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()
The following code only works if I comment out the initialiser.
class What:
def __init__(self):
pass
def method1(self):
print 'method1'
def main():
b = What()
if hasattr(b,"method1"):
print "b.method1"
b.method1()
main()
If it's not commented out I get the error message…
Traceback (most recent call last):
File "strange.py", line 17, in <module>
main()
File "strange.py", line 15, in main
b.method1()
AttributeError: What instance has no attribute 'method1'
However if I type in an identical method and call it, there is no problem at all…
def method2(self):
print 'method2'
I've od -c the file and there are no strange characters in the text
Using Python 2.7.2
I think you are mixing tabs and spaces.
With the code using 4 spaces per indent (spaces in accordance with pep8) it works fine. But this
class What:
def __init__(self):
pass
def method1(self):
print 'method1'
def main():
b = What()
if hasattr(b,"method1"):
print "b.method1"
b.method1()
main()
Is what Python would see if you had tabs for method1, and this will generate the error you see.
Hi I am trying to make a Logfile for my class that anything happens to be written in there...
here is how my class looks like
class MyClass:
f = open('Log.txt','a')
def __init__(self):
self.f = open('Log.txt', 'a')
self.f.write("My Program Started at "+str(datetime.datetime.now())+"\n")
def __del__(self):
self.f.write("closing the log file and terminating...")
self.f.close()
my code works, but as you see above I have two f=open('Log.txt','a')
is there any way to avoid that ?
I tried to delete one of them but it would yell at me... is there any better way to do this?
You should have only one.
The first f=... creates the file handler as a class attribute at import time, so the first time you instantiate MyClass you have the handler open, but:
MyClass() # and __del__ is called here
MyClass() # f is closed
ValueError: I/O operation on closed file
If you do it at the __init__ method creates the handler as a instance attribute and opens the file every time you instantiate MyClass(), probably this is what you want, except if you want to use the class without instantiating it.
What about something like this:
class Test:
def __init__(self): #open the file
self.f=open("log.txt", "w") #or "a"
def mywrite(self, mytext): #write the text you want
self.f.write("%s\n" % mytext)
def myclose(self): #close the file when necessary (you don't need to delete the object)
self.f.close()
myFile=Test()
myFile.mywrite("abcd")
myFile.myclose()
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()