Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

haakon Guttormsen
haakon Guttormsen
2,157 Points

How to import a package to a class in python

I want to import a package named tsp to my class named 'Tour'. When I run the file without a class and a method, it works well. Tsp is an algorithm for finding the fastest route through a given list of cities and the distances between them. But I want to implement this using Object oriented programming. When I try to run the code I get the following message: "AttributeError: module 'tsp' has no attribute 'tsp':" So my question is, how can I import 'tsp' to my class 'Tour'?

import tsp

class Tour:
    def fastestWay(self):
        A = []
        B=[   0,6.47, 7.10, 6.10,3.65 ]   # Oslo
        C=[7.14,   0, 4.42, 9.30,7.39 ]   # Bergen
        D=[   7,4.48,    0,13.37,3.14 ]   # Stavanger
        E=[6.24,9.34,13.36,    0,10.12]   # Trondheim
        F=[ 4.3,7.45, 3.33,10.17,   0 ]   # Kristiansand

        r = range(len(A))
        # Dictionary of distance
        dist = {(i, j): A[i][j] for i in r for j in r}
        #print(tsp.tsp(r, dist))
        print(tsp.tsp(r,dist))
i=Tour()
i.fastestWay()

2 Answers

haakon Guttormsen
haakon Guttormsen
2,157 Points

The problem was that I had a file called 'tsp.py' in my directory. Therefore it imported the file instead of the package. All I had to do was to rename the tsp.py. Then it worked well.

Haisam Elkewidy
Haisam Elkewidy
26,987 Points

have you tried this?

from tsp import *