Jupyter - importing class from an imported notebook - python

I'm trying to import a class from another notebook and following this tutorial I am doing something wrong which i don't get.
I have
#(Building.ipynb)
class Class ():
def __init__ ():
"this is my class"
print ("I am a new class instance")
and all the code exactly as in the tutorial.
When I try:
sys.meta_path.append(NotebookFinder())
import Building
a = Class()
#(or)
a = Building.Class()
I get:
NameError Traceback (most recent call last)
<ipython-input-82-ecc443c1045a> in <module>()
1 sys.meta_path.append(NotebookFinder())
2 import Building
----> 3 a = Class()
4 #(or)
5 a = Building.Class()
NameError: name 'Class' is not defined
What's wrong here?

Simply delete the line a = Class() since the correct way to call your Class constructor is Building.Class(), which you had, but your code fails before it can run the correct code.
Also - you'll need to change def __init__(): to def __init__(self): since __init__ needs a reference to itself.

Related

Importing a class by referring to it with a variable?

Edit: This question was on the assumption that I could import parts of modules without importing the whole module. It turns out that isn't the case so I decided to just import the whole module with from ex45_extras import * anyway. That makes this question pointless, but I decided to not delete this question so that some other beginner with the same question can come here and find out the sad truth: You can't import modules as parts anyways
The following is the original question:
I'm a beginner so sry for the noob question. I want to call specific classes from a module with a variable. I don't want to call the whole module. And I need to do this using this class Nav() to control which classes are being imported. Is there a way to do this? Or is there a better solution?
class Nav():
def __init__(self):
print("This is class Nav")
def play(self):
current_scene_name = "A()" # this is where the variable is defined
from ex45_extras import current_scene_name # <- this is the one
x = Nav()
x.play()
Currently it's raising this error:
This is class Nav
Traceback (most recent call last):
File "D:\Programming\Python\LPTHW_Exs\ex45\test.py", line 11, in <module>
x.play()
File "D:\Programming\Python\LPTHW_Exs\ex45\test.py", line 7, in play
from ex45_extras import current_scene_name
ImportError: cannot import name 'current_scene_name' from 'ex45_extras' (D:\Programming\Python\LPTHW_Exs\ex45\ex45_extras.py)
Class names don't have a trailing () suffix — that's how you create an instance of one (i.e. by calling it).
Anyhow, if ex45_extras.py defines a class named A:
class A:
pass
Then you could import the class via a string containing its name, and then create an instance of it as shown below:
class Nav():
def __init__(self):
print("This is class Nav")
def play(self):
import ex45_extras
current_scene_name = 'A' # this is where the variable is defined
class_ = getattr(ex45_extras, current_scene_name) # Get class.
instance = class_() # Create instance of class.
print(f'{instance=}') # -> instance=<ex45_extras.A object at 0x010D4838>
x = Nav()
x.play()
guess it's because you're trying to import an string "A()" instead of a class A()

NameError: class name is not defined, despite being imported

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

Python Inheritance initialize problems

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.&lowbar;&lowbar;init&lowbar;&lowbar;() 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.

Global name not defined error in Python

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

Python class can't see method unless I comment out __init__

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.

Categories

Resources