首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >调用之前引用局部变量。

调用之前引用局部变量。
EN

Stack Overflow用户
提问于 2022-03-23 15:35:04
回答 1查看 32关注 0票数 0

我收到的错误是UnboundLocalError:赋值前引用的局部变量'this_mammal‘

我已经练习了几天了,但这让我很困惑。我四处寻找凹痕,到处都有this_mammal,但似乎没什么问题。我不能包括哺乳动物超类和动物子类,因为我没有足够的文本来包含所有的代码。如果有必要的话,请让我知道!我可以试试。

代码语言:javascript
复制
def select_which_mammal():
    print("Welcome to the Mammal Inventory Management System!")
    print()
    print("1. Cow")
    print("2. Cat")
    print("3. Dog")
    print("4. Human")
    print("5. Platypus")
    print("6. Echidna")
    print("7. Bat")
    print()
    selection = int(input("Enter the number for the mammal you would like to add:"))

    while selection < 1 or selection > 7:
        print("ERROR: Selections must be 1-7.")
        selection = int(input("Enter the number for the mammal you would like to add:"))

def create_the_mammal(mammal_type):
    
    if mammal_type == 1: this_mammal = Mammal('Cow', 4, 3)
    
    elif mammal_type == 2: this_mammal = Mammal('Cat', 4, 9)

    elif mammal_type == 3: this_mammal = Mammal('Dog', 4, 6)

    elif mammal_type == 4: this_mammal = mammal("Human", 2, 14)
    
    elif mammal_type == 5: this_mammal = mammal("Platypus", 4, 3)

    elif mammal_type == 6: this_mammal = mammal("Echidna", 4, 3)

    elif mammal_type == 7: this_mammal = mammal("Bat", 2, 1)

    print("\nYour", this_mammal.get_name(), "has been added to the system.\n")
    
    return this_mammal

def choose_an_action(this_mammal): 
    print("Next, please choose an action for your ", this_mammal.get_name() + ".")
    print()
    print("1. Display the mammal's status")
    print("2. Hear the mammal's sound")
    print("3. Go out for a walk with your mammal")
    print("4. Breed your mammal")
    print()
    action = int(input("Enter the number for the action:"))

    while action < 1 or action > 4:
        print("ERROR: Selections must be 1-4.")
        action = input(int("Enter the number for the action:"))

    if action == 1: this_mammal.show_self()

    elif action == 2: this_mammal.make_sound()

    elif action == 3: this_mammal.ambulate()

    elif action == 4: this_mammal.reproduce()

def main():

    new_mammal = select_which_mammal()

    this_mammal = create_the_mammal(new_mammal)

    choose_an_action(this_mammal)

main()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-23 15:41:03

您必须在return selection函数的末尾进行select_which_mammal

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71589978

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档