1

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 ?

Blue
  • 22,608
  • 7
  • 62
  • 92
Cobako
  • 37
  • 8
  • Possible duplicate of [Sibling package imports](https://stackoverflow.com/questions/6323860/sibling-package-imports) – Thomas Lang Nov 29 '18 at 05:32
  • This topic didn't really solved my problem since it not working ... – Cobako Nov 29 '18 at 05:55
  • Don't edit answers into the questions, as they invalidate the answers below. Instead, add an answer below, and mark it as accepted if it solves your issue. – Blue Nov 29 '18 at 07:26

2 Answers2

1

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
Samuel Kazeem
  • 787
  • 1
  • 8
  • 15
0

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.

Lê Tư Thành
  • 1,063
  • 2
  • 10
  • 19