Cobako
Cobako

Reputation: 37

How to import a class into a python file from an outside directory?

I'm fairly new to python and currently struggling to do the simple thing of importing a file from an outside directory.

Let's consider two files :

// src/class/Rider ....

class Rider(object) :
    def __init__(self, firstname, lastname, emailaddress, phonenumber, pickuplocation, dropofflocation, pickuptime, dropofftime):
        self.FirstName = firstname
        self.LastName = lastname
        self.EmailAddress = emailaddress
        self.PhoneNumber = phonenumber
        self.PickUpLocation = pickuplocation
        self.DropOffLocation = dropofflocation
        self.PickUpTime = pickuptime
        self.DropOffTime = dropofftime

    def set_rider_name(self):
        first = self.FirstName
        last = self.LastName
        return first + last

and

//src/method/rider

# importing Rider class in here ...

I'm struggling to import the Rider class from src/class/Rider into the src/method/rider file so I can actually use that class.

Coming from node.js and being used to the import/export of es6 , I'm still learning python 2.7.

my root directory is something like : ../Golf-cart/src , where I have class and method subdirectories inside src/

How can I import my class definition into my method file so I can actually use it there ?

Upvotes: 1

Views: 1906

Answers (2)

Lê Tư Thành
Lê Tư Thành

Reputation: 1083

You can create the empty file __init__.py in both directories /src/class/__init__.py and /src/method/__init__.py.

Then you just import like

#/src/method/rider.py

import class.Rider
...

That's it. Hope it help.

Upvotes: 0

Samuel Kazeem
Samuel Kazeem

Reputation: 805

You might want to use sys to add the directory to the system path, then you can import the file directly.

import sys
sys.path.insert(0, 'system/path/to/Rider')
import Rider

Upvotes: 1

Related Questions