NameError: class name is not defined, despite being imported - python

I wrote a project with Spyder which contains several module files, such as tester.py and scheduler.py. I created the following classes in tester.py:
class Tester(object):
def run(self):
pass
When I imported Tester class to the scheduler.py, I got a name error(I used Anaconda Prompt to access the project folder and run python scheduler.py):
from tester import Tester
class Scheduler():
def schedule_tester(self):
getter = Tester()
while True:
getter.run()
if __name__ == '__main__':
scheduler = Scheduler()
scheduler.schedule_tester()
Traceback (most recent call last):
NameError: name 'Tester' is not defined
Can someone help me figure out, many thanks!

Your scheduler class instantiates getter as an instance of the Tester class.
Then you try to use the run method on the imported Tester class.
This is impossible since it is a normal method and not a classmethod.
I think you want to call getter.run() instead of Tester.run() in your while loop.
So your Scheduler would look like this:
class Scheduler():
def schedule_tester(self):
getter = Tester()
while True:
getter.run() # not Tester.run()

Related

Python, define global variable in a class and import this class for main script,but that global variable is not defined

I have a basic.py file under a specific folder which defined a class:
class test_function:
def loop_unit(self,str):
global test_list
test_list.append(str)
I have another main.py which have following code
from folder import basic
test_list=[]
object=basic.test_function()
object.loop_unit('teststr')
print(test_list)
it will give an error says
name 'test_list' is not defined(it trackback to test_list.append(str) )
I actually defined global variable in the function, and I defined it at the start of the main code, why it still said this is not defined?
You defined main.test_list; test_function.loop_unit wants basic.test_list.
from folder import basic
basic.test_list = []
object = basic.test_function()
object.loop_unit('teststr')
print(basic.test_list)
Try to do this in your class definition:
class test_function:
def __init__(self):
self.test_list = []
def loop_unit(self,str):
sel.test_list.append(str)
from folder import basic
#test_list=[] --remove this line
object=basic.test_function()
object.loop_unit('teststr')
#print(test_list) ---remove this line but add this:
print(object.test_list)
Try and tell me if it works.

passing self with other argument on function call python

I have a little problem, I have my code below.
I want to call the "speak" function with two arguments inside the main() class.
When I call speak it says that self its not defined, and i don't know how to make it work...
Any ideas?
class main():
def blueon(self):
print("teste")
def speak(self,fala):
self.blueon
print(fala)
speak("testeaaaaa")
Try something like this.
Comments explain changes
class Main: # Class name capitalized and no parenthesis if the class has no base classs
def __init__(self): # class constructor. Initialize here your variables
pass
# if you have a function that doesn't use self, you can declare it static
#staticmethod
def blueon():
print("teste")
def speak(self, fala):
self.blueon() # added missing parenthesis
print(fala)
if __name__ == "__main__": # add this so you can later import your class as a library without executing your test code
m = Main() # instantiate the class
m.speak("testeaaaaa") # call the speak method
You run speak() in wrong way.
First you have to create instance of class m = main() and later use m.speak("text").
And you have to do with different indetation.
BTW: There is good rule to use CamelCaseName for classes - class Main(): - it helps to recognize class in code, and it allows to do main = Main().
More in PEP 8 -- Style Guide for Python Code
# --- classes ---
class Main():
def blueon(self):
print("teste")
def speak(self, fala):
self.blueon() # you forgot `()
print(fala)
# --- main ---
main = Main()
main.speak("testeaaaaa")

class declaration in exec inits class, but functions don't work

I am going to attach two blocks of code, the first is the main code that is ran the second is the testClass file containing a sample class for testing purposes. To understand what's going on it's probably easiest to run the code on your own. When I call sC.cls.print2() it says that the self parameter is unfulfilled. Normally when working with classes, self (in this case) would be sC.cls and you wouldn't have to pass it as a parameter. Any advice is greatly appreciated on why this is occuring, I think it's something to do with exec's scope but even if I run this function in exec it gives the same error and I can't figure out a way around it. If you'd like any more info please just ask!
import testClass
def main():
inst = testClass.myClass()
classInfo = str(type(inst)).split()[1].split("'")[1].split('.')
print(classInfo)
class StoreClass:
def __init__(self):
pass
exec('from {} import {}'.format(classInfo[0], classInfo[1]))
sC = StoreClass()
exec('sC.cls = {}'.format(classInfo[1]))
print(sC.cls)
sC.cls.print2()
if __name__ == '__main__':
main()
class myClass:
def printSomething(self):
print('hello')
def print2(self):
print('hi')

Python - Function isn't 'Global' and so can't be called within Threading Class

So, first off here's my code:
import threading
print "Press Escape to Quit"
class threadOne(threading.Thread): #I don't understand this or the next line
def run(self):
setup()
def setup():
print 'hello world - this is threadOne'
class threadTwo(threading.Thread):
def run(self):
print 'ran'
threadOne().start()
threadTwo().start()
So, the problem is that within my class 'threadOne' the run function runs (as that is called by the threading module) but from there I can not called any other functions. That includes if I make more functions beneath the setup() function. For example above, in my run(self) function I try and call setup() and get 'NameError: global name 'setup' is not defined'.
Does anybody have any ideas or can they explain this to me?
Sam
setup is a method of your Thread instance. Therefore, you call it with self.setup() rather than setup(). The latter is trying to call a global function named setup which does not exist.
Since setup() is an instance method, it must accept self as its first parameter as well.
I assume you meant to do the following:
class threadOne(threading.Thread): #I don't understand this or the next line
def run(self):
self.setup()
def setup(self):
print 'hello world - this is threadOne'

initializing python class globally?

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()

Categories

Resources