Python OOP - 方法返回 None

标签 python oop

我正在尝试用 Python OOP 拼凑一个小作业,但我不确定我错在哪里。

我有两个类(class):鞋业和商店。 在 Shoe 类中,我只创建了 Shoe,而 Store 类是我执行所有方法的地方。

我正在尝试创建一个“添加鞋子”方法,该方法将检查鞋子是否存在于给定列表中,如果不存在,则会添加它。我通过比较shoeID来检查鞋子是否存在。对象。

这是我的代码:

class Shoe(object):
    def __init__(self, shoeID, shoePrice, shoeSize, quantity):
        self.shoeID = shoeID
        self.shoePrice = shoePrice
        self.shoeSize = shoeSize
        self.quantity = quantity

    def __str__(self):
        return "Shoe ID:", self.shoeID, "Shoe Price:", str(self.shoePrice), "Shoe Size:", str(self.shoeSize), "Quantity:", str(self.quantity)

class Store(object):
    def __init__(self):
        self.shoeList = []

    def __str__(self):
        return "Shoe list: " + self.shoeList

    def add_shoe(self, newShoe):
        for i in self.shoeList:
            if i.shoeID == newShoe.shoeID:
                print("Shoe already exists, updating quantity")
                i.quantity += newShoe.quantity
            else:
                print("This is a new shoe, adding it to the list")
                self.shoeList.append(i)
            return

这是我的测试仪:

import shoes

testStore = shoes.Store()
shoe1 = shoes.Shoe(123, 100, 40, 2)

print(testStore.add_shoe(shoe1))

我的输出始终是 None 。我尝试改变很多东西,但我想我只是错过了一些我看不到的愚蠢的东西。 我很想获得一些帮助。

谢谢!

最佳答案

你的代码有很多问题。我修复了所有

class Shoe(object):
    def __init__(self, shoeID, shoePrice, shoeSize, quantity):
        self.shoeID = shoeID
        self.shoePrice = shoePrice
        self.shoeSize = shoeSize
        self.quantity = quantity

    def __str__(self):
        return "Shoe ID: {} Shoe Price: {} Shoe Size: {} Quantity: {}".format(self.shoeID, str(self.shoePrice),str(self.shoeSize), str(self.quantity)) 


class Store(object):
    def __init__(self):
        self.shoeDict = {}

    def __str__(self):
        return "Shoe list: " + "\n".join([str(i) for i in self.shoeDict.values()])

    def add_shoe(self, newShoe):
        if newShoe.shoeID in self.shoeDict:
            print("Shoe already exists, updating quantity")
            self.shoeDict[newShoe.shoeID].quantity += newShoe.quantity
        else:
            print("This is a new shoe, adding it to the list")
            self.shoeDict[newShoe.shoeID] = newShoe
        return

testStore = Store()
shoe1 = Shoe(123, 100, 40, 2)

testStore.add_shoe(shoe1)
testStore.add_shoe(Shoe(123, 100, 40, 2))
print(testStore)

这是一款新鞋,正在将其添加到列表中 鞋子已存在,正在更新数量 鞋子 list : 鞋子 ID:123 鞋子价格:100 鞋子尺码:40 数量:4

关于Python OOP - 方法返回 None,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57610967/

相关文章:

python - 使用还包含科学数字格式的 python 将逗号转换为 txt 中的点

O(n) 时间的 Python Fibonacci 递归(而不是迭代)?

python - 替代Python中的类对象

php - 直接显示方法返回的数组的值

php - 使用现有 ISBN 和 PHP 的书籍封面

php - PDO 不执行语句

python - 根据数组值的最大总和对字典进行排序

python - 在python中使用正则表达式搜索三个不同的单词

python - 遍历以数字开头的行

javascript - 修复此测试 : Functional-Reactive Programming Tutorial