Reputation: 20856
I have defined 2 classes- Person & Manager. The Manager inherits the Person class. I get a error while trying to import the Person class..
Code is give below.
Person.py
class Person:
def __init__(self, name, age, pay=0, job=None):
self.name = name
self.age = age
self.pay = pay
self.job = job
def lastname(self):
return self.name.split()[-1]
def giveraise(self,percent):
#return self.pay *= (1.0 + percent)
self.pay *= (1.0 + percent)
return self.pay
Manager.py
from Basics import Person
class Manager(Person):
def giveRaise(self, percent, bonus=0.1):
self.pay *= (1.0 + percent + bonus)
return self.pay
Error statements:
C:\Python27\Basics>Person.py
C:\Python27\Basics>Manager.py Traceback (most recent call last): File "C:\Python27\Basics\Manager.py", line 1, in from Basics import Person ImportError: No module named Basics
Why do I get the No module found error?
Upvotes: 2
Views: 13304
Reputation:
from Basics import Person
should be from Person import Person
. You don't have a Basics.py module to import from.
Upvotes: 0
Reputation: 22007
You should look up how import and PYTHONPATH work. In your case, you can solve that using:
from Person import Person
I see you're coming from a Java background (where each file must have a class with the same name of the file), but that's not how Python modules work.
In short, when you run a Python script from the command line, as you did, it looks for modules (among other places) in your current dir. When you import a (simple) name like you did, Python will look for:
Basic.py
; or:__init__.py
.Then it will look for a definition inside that module named Person
.
Upvotes: 7
Reputation: 129001
You defined the Person
class in a file named Person.py
. Therefore, you should import it like this:
from Person import Person
Note that it's the convention in Python to have lowercase module names. For example, rename Person.py
to person.py
and Manager.py
to manager.py
. Then you'd import the Person
class like this:
from person import Person
If the person
module is part of a package, you'd probably want to import like this:
from .person import Person
This will ease the transition to Python 3.
Upvotes: 3
Reputation: 798746
Because it's in Person.py
, not Basics.py
.
from Person import Person
Upvotes: 4