Jonathan Spirit
Jonathan Spirit

Reputation: 599

Calling a function from another file in Python

Yes, this question has been asked before. No, it did not answer my question satisfactorily. So, I'm creating my Giraffe Program in Python first (don't ask) and I'm trying to get the user to name their giraffe.

My files are all in one package called code. In the file Main_Code, the function createGiraffe is called from code.Various_Functions. Here is my code.

import code
print("Welcome to The Animal Kingdom.")
userGiraffe = code.Various_Functions.createGiraffe()

And the code in code.Giraffes:

import code
def createGiraffe():
    print("Name your giraffe.")
    GiraffeName = input()
    return GiraffeName

However, when I run Main_Code, it gives me this error:

Traceback (most recent call last):
  File "C:\Users\Jonathan\Documents\Aptana Studio 3 Workspace\The Animal Kingdom\src\code\Main_Code.py", line 3, in <module>
    userGiraffe = code.Giraffes.Giraffes.createGiraffe()
AttributeError: 'module' object has no attribute 'Giraffes'

How do I fix this? I believe that I've done everything by the book. It's all using the same package so I can call the function, I'm calling it from the right place, and the function has no syntax errors. Can anyone help with this?

Upvotes: 0

Views: 1846

Answers (2)

greg
greg

Reputation: 1416

When you call function like:

userGiraffe = code.Giraffes.Giraffes.createGiraffe()

it means you have a project in dir code with internal dir Giraffes and module Giraffes with function createGiraffe. Is this your exception?

Upvotes: 0

piokuc
piokuc

Reputation: 26164

Do

import code.Giraffes

before executing the offending line:

userGiraffe = code.Giraffes.Giraffes.createGiraffe()

Upvotes: 2

Related Questions