Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inherit class from different file?

Tags:

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.

like image 861
D1X Avatar asked Oct 25 '16 10:10

D1X


2 Answers

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
like image 190
Angus Williams Avatar answered Sep 21 '22 19:09

Angus Williams


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:

  • Importing a function from a class in another file?
  • What is __init__.py for?
like image 45
Moinuddin Quadri Avatar answered Sep 17 '22 19:09

Moinuddin Quadri