如何修复python3中“NoneType”的属性错误?

2024-06-16 15:01:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个函数,通过使用类来合并两个字典,但我无法创建,因为我一直得到一个AttributeError“NoneType”。但是,当单独运行代码而不使用整个代码时,该函数可以工作,这让我很困惑。 我的全部代码是:

prices = {
    "apple": 1,
    "beets": 1,
    "carrots": 1}

cookbook={}

total=20


def handle_commands():
    keep_going=True
    while keep_going:
        choices=input("$ ").strip().lower().split()
        command=choices[0]
        if command == "loadrecipefile":
            recipe_file=choices[1]
            loadrecipefile(recipe_file)
        elif command == "printrecipes":
            printrecipes()
        elif command == "printiinventory":
            printiinventory()
        elif command == "printmoney":
            printmoney()
        elif command == "preparedish":
            recipe_name=choices[1]
            preparedish(recipe_name)
        elif command == "buyingredient":
            name=choices[1]
            number=int(choices[2])
            buyingredient(name, number)
        elif command == "setprices":
            apple_price=int(choices[1])
            beets_price=int(choices[2])
            carrots_price=int(choices[3])
            setprices(apple_price, beets_price, carrots_price)
        elif command == "mergerecipes":
            r1=choices[1]
            r2=choices[2]
            mergerecipes(r1,r2)
        elif command == "quit":
            keep_going=False
            break
        else:
            print("Sorry that is not an acceptable command")
    return 

def loadrecipefile (recipe_file):
    infile=open(recipe_file)
    Linelist=infile.readlines()
    for line in Linelist:
        wordList=line.split()
        r1=Recipe(wordList[0],int(wordList[1]),int(wordList[2]),int(wordList[3]))
        cookbook.addRecipe(r1)

def printrecipes():
    for recipe in cookbook.allRecipes():
        print(recipe.getName(),int(recipe.getApples()),int(recipe.getBeets()),int(recipe.getCarrots()))

def buyingredient(name, number:int):
    global total
    if number*prices[name] > total:
        print("Not enough cash!")
    if iinventory == 'apple':
        iinventory.getApples()
    elif iinventory == 'beets':
        iinventory.getBeets()
    elif iinventory == 'carrots':
        iinventory.getCarrots()

    iinventory[name] += number
    total -= number*prices[name]

def printiinventory():
    print(int(iinventory.getApples()), int(iinventory.getBeets()), int(iinventory.getCarrots()))

def printmoney():
    print(total)

def CanPrepareDish(recipe_name):
    recipe = cookbook[recipe_name]
    for ingred in recipe:
        if ingred not in iinventory:
            return False
        if iinventory[ingred] < recipe[ingred]:
            return False
    return True

def preparedish(recipe_name):
    if not CanPrepareDish(recipe_name):
        print("Not enough ingredients")
    else:
        recipe = cookbook[recipe_name]
        for ingred in recipe:
            iinventory[ingred] -= recipe[ingred]
        if recipe_name in iinventory:
            iinventory[recipe_name] +=1
        else:
            iinventory[recipe_name] = 1
            print("Dish prepared")

    #for recipe in cookbook.allRecipes():
        #if recipe_name == recipe.getName():


def setprices(apple_price, beets_price, carrots_price):
    for name,value in prices.items():
        prices["apple"] = apple_price
        prices["beets"] = beets_price
        prices["carrots"] = carrots_price

def mergerecipes(r1,r2):
    dish1 = cookbook.getRecipe(r1)
    dish2 = cookbook.getRecipe(r2)
    name = dish1.getName() + dish2.getName()
    apple_num = dish1.getApples() + dish2.getApples()
    beet_num = dish1.getBeets() + dish2.getBeets()
    carrot_num = dish1.getCarrots() + dish2.getCarrots()
    rnew=Recipe(name,apple_num,beet_num,carrot_num)

class Recipe:
    def __init__(self,name,apple_num,beet_num,carrot_num):
        self.name=str(name)
        self.apple_num=int(apple_num)
        self.beet_num=int(beet_num)
        self.carrot_num=int(carrot_num)
    def getName(self):
        return self.name
    def getApples(self):
        return self.apple_num
    def getBeets(self):
        return self.beet_num
    def getCarrots(self):
        return self.carrot_num

class Iinventory:
    def __init__(self):
        self.apple_num=0
        self.beets_num=0
        self.carrots_num=0
    def getApples(self):
        return int(self.apple_num)
    def getBeets(self):
        return int(self.beets_num)
    def getCarrots(self):
        return int(self.carrots_num)

iinventory=Iinventory()

class Cookbook:
    def __init__(self):
        self.Cooklist=[]
    def addRecipe(self,Recipe):
        self.Cooklist.append(Recipe)
    def getRecipe(self,recipe_name):
        for recipe in self.Cooklist:
            if recipe_name == recipe.getName():
                return recipe
    def allRecipes(self):
        for Recipe in self.Cooklist:
            return self.Cooklist

cookbook=Cookbook()

handle_commands()

但是这个函数只能和代码合并。我想知道为什么和如何修复我的代码错误,使该函数在我的整个代码中工作。在

我的整个代码片段:

^{pr2}$

所以当我加载一个文本文件时,它会把“食谱”输入到烹饪书中,然后你就可以看到印刷食谱了。在

输出示例如下:

loadrecipefile('recipes.txt')        
printrecipes() 
Dish1 2 4 1
Dish2 2 2 2
Dish3 1 2 4
Dish4 0 2 1
mergerecipes('Dish1','Dish3')
printrecipes() 
Dish1 2 4 1
Dish2 2 2 2
Dish3 1 2 4
Dish4 0 2 1
Dish1Dish3 3 6 5

**如果混淆:我在运行整个代码时尝试运行合并配方,但得到以下错误:

$ loadrecipefile recipes.txt
$ printrecipes
Dish1 2 4 1
Dish2 2 2 2
Dish3 1 2 4
Dish4 0 2 1
$ mergerecipes Dish1 Dish2
name = dish1.getName() + dish2.getName()
AttributeError: 'NoneType' object has no attribute 'getName'

我们将不胜感激


Tags: nameinselfapplereturndefrecipeprice