找不到错误:从库中调用项目

时间:2018-01-24 23:09:04

标签: python python-3.x function class dictionary

我遇到一个问题,即调用要在类“山”中的定义中添加的变量。它运行错误:

属性错误:'功能'对象没有属性'图片'

以下是代码:

import random
class currencies:
    film = 5
class pictures:
    picture = {"m_goat": 0, "b_eagle": 0, "marmot": 0, "r_snake": 0, "m_lion": 0, "b_dragon": 0, "vulture": 0}
class location:
    city = True
    shop = False
    mountains = False
    desert = False
class mountain:
    #Travel to mountains
    def travel_m():
        print("You climb to the top of a tall mountain")
        location.mountains = True
        animals = ["mountain goat", "bald eagle", "marmot", "rattlesnake", "mountain lion"]
    animal_pics = ["m_goat", "b_eagle", "marmot", "r_snake", "m_lion"]
    if 1 == 1: #for simplicity I changed this to a non random number
        animal = random.randint(0, 4)
        str_animal = animals[animal]
        ans = input("You see a wild " + str_animal + ". Would you like to take a photo? (y/n) \n")
        if ans == "y" and currencies.film == 0:
            print("You cannot take a picture of this animal because you are out of film")
        elif ans == "y":
            currencies.film -= 1
            pictures.picture[animal_pics] = pictures.picture[animal_pics] + 1 #this is the line with the error
            print("You took a picture of the animal")
        elif ans == "n":
            print("The animal was left unbothered")
        else:
            print("I do not recognize that command")  
def pictures():
    print("You have " + str(pictures.pictures['m_goat']) + " picture(s) of mountain goats")
    print("You have " + str(pictures.pictures['b_eagle']) + " picture(s) of bald eagles")
    print("You have " + str(pictures.pictures['marmot']) + " picture(s) of marmots")
    print("You have " + str(pictures.pictures['r_snake']) + " picture(s) of rattlesnakes")
    print("You have " + str(pictures.pictures['m_lion']) + " picture(s) of mountain lions")
    mountain.travel_m()

感谢您提供任何帮助。我只是在学习这门语言,但我和我的老师都无法在网上找到答案。如果它是愚蠢的,请说

1 个答案:

答案 0 :(得分:3)

当你这样做时:

def pictures():

您正在重新定义变量pictures。它现在命名函数,而不是之前定义的类。

为函数指定一个与类不冲突的名称,例如

def show_pictures():

此外,在最后一个功能中使用pictures.pictures。那应该是pictures.picture

修正后,这一行是错误的:

pictures.picture[animal_pics] = pictures.picture[animal_pics] + 1

animal_pics是一个列表,您不能将其用作字典键。我想你的意思是:

pictures.picture[str_animal] += 1