I have two files:
fig.py
import math
PI=math.pi
class Fig:
def __init__(self):
self.name= " "
And
circle.py
class Circle(Fig):
def __init__(self, radius):
self.name= "Circle"
self.data= ["Radius: ", radius]
But I am trying to load them I whenever I try it jupyter-notebook throws the error:
NameError: name 'Fig' is not defined
I have tried using import fig
at the beggining of circle.py and it does not work, neither does running both files. They are both in the same directory.
Ok it's not exactly clear what's going wrong because you haven't sent us precisely what you are doing, but here is my guess. If your circle.py
file is as follows
import fig
class Circle(Fig):
def __init__(self, radius):
self.name= "Circle"
self.data= ["Radius: ", radius]
This will break because python doesn't know where to find Fig
. If instead you write
import fig
class Circle(fig.Fig):
def __init__(self, radius):
self.name= "Circle"
self.data= ["Radius: ", radius]
or
from fig import Fig
class Circle(Fig):
def __init__(self, radius):
self.name= "Circle"
self.data= ["Radius: ", radius]
Everything should work fine. This is because you either have to tell python the namespace through which it can access the class (my first solution) or explicitly import the class (my second solution). The same logic applies if you want to use PI
:
import fig
class Circle(fig.Fig):
def __init__(self, radius):
self.name= "Circle"
self.data= ["Radius: ", radius]
#use PI from fig.py by informing python of namespace
self.circumference = 2.*fig.PI*radius
or
from fig import Fig, PI
class Circle(fig):
def __init__(self, radius):
self.name= "Circle"
self.data= ["Radius: ", radius]
#PI is now explicitly imported so don't need namespace
self.circumference = 2.*PI*radius
You need to do from fig import FIG
in your circle.py. Also make sure that you have __init__.py
file present in the folder which is having circle.py and fig.py.
Please also take as look at:
__init__.py
for?If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With