Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python class definition--import statement

Tags:

python

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?

like image 924
user1050619 Avatar asked Jun 10 '26 06:06

user1050619


1 Answers

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:

  1. A file named Basic.py; or:
  2. A folder named Basic with a file named __init__.py.

Then it will look for a definition inside that module named Person.

like image 182
mgibsonbr Avatar answered Jun 11 '26 20:06

mgibsonbr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!