简体   繁体   English

从Python中的另一个文件调用函数

[英]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. 所以,我首先用Python创建我的长颈鹿程序(不要问),我试图让用户命名他们的长颈鹿。

My files are all in one package called code . 我的文件都在一个名为code包中。 In the file Main_Code , the function createGiraffe is called from code.Various_Functions . 在文件Main_Code ,功能createGiraffe从所谓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: 但是,当我运行Main_Code时,它给了我这个错误:

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? 有人能帮忙吗?

Do

import code.Giraffes

before executing the offending line: 在执行违规行之前:

userGiraffe = code.Giraffes.Giraffes.createGiraffe()

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 . 这意味着你有一个dir code的项目,内部目录Giraffes和模块Giraffes与功能createGiraffe Is this your exception? 这是你的例外吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM