About importing modules in python
I have three modules in the same folder.
The first module, run.py, is the main program.
The second module, called shapes.py, contains a class called "Shape"
The third module, called circles.py, that contains a class called "Circle" which inherits from Shape.
The code is written as follows
run.py
from shapes import Shape from circles import Circle a = Circle() a.print_test()
shapes.py
class Shape(object): def print_name(self): print "I am a generic shape"
circles.py
class Circle(Shape): def print_name(self): print "I am a circle"
I want to be able to run the program and have the console say "I am a circle", but it throws an exception when importing circles saying that "Shape is not defined".
I can always tell circles.py to import the Shape class, but that's not what I want. What if they're not in the开发者_高级运维 same folder? What if there's a complicated hierarchy of folders?
It feels like I'm importing the shapes module twice that way unnecessarily just so that I can import circles.
What can I do? (well, in this case, run.py probably doesn't even need to import Shape, but if I had some other modules "triangles", "hexagons", and "pentagons" I don't want them all to have to import Shape)
EDIT: I could also just put them all in the same module cause they're shapes! But this sort of problem might arise some time.
Import shapes
from within circles.py
:
from shapes import Shape
class Circle(Shape):
...
In Python, each module must import
whatever it needs. It can't rely on any other module to do the importing for it.
You need to import all classes you are using in a python module. In your first module (run.py
) you are not using Shape
, only Circle
, so you can omit it there. run.py
does not need to know how Circle
s are defined at all.
In circles.py
however, you do need to import shapes
, as you are basing your Circle
class on the Shape
class, so it needs to have access to the definition there.
from shapes import Shape
class Circle(Shape):
def print_name(self):
print "I am a circle"
I'd recommend you use a tool like pyflakes to check your files for errors like these. You can hook such a script up with various editors to be run automatically, giving you instant feedback whenever you save your python files.
I think you have to initialize the shapes superclass in the circle class. You can do this via constructors. So in your circle.py class you would need to have something like the following:
class Circle(Shapes):
def __init__(self):
Shapes.__init__(self)
# put the rest of your circle code here.
Magnus Lie Hetland's book, "Beginning Python: From Novice to Professional" covers this area fairly well.
精彩评论