You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决TypeError: GroceryInventory.__str__()缺少必需参数self的问题?

问题定位与错误原因

核心错误点

测试代码中的这一行触发了报错:

print(GroceryInventory.__str__())

错误原因

__str__是Python的实例方法,这类方法的第一个参数必须是self(代表当前类的实例对象)。当你直接通过GroceryInventory类调用__str__时,Python不会自动传入实例对象,因此缺少了self这个必填参数,进而触发TypeError。

修复方案

1. 修正__str__的调用方式

将类调用改为通过实例调用,直接打印实例即可(print会自动触发实例的__str__方法):

for item in shopping_list:
    print(item)  # 替代原错误的print(GroceryInventory.__str__())
    print(f'\tUnit Price: ${item.calc_unit_price():.2f}')

2. 修复order_note方法的冗余参数

order_note方法定义了quantityout和quantityin参数,但内部实际使用的是实例自身的属性,这两个参数完全多余,修改后如下:

def order_note(self):
    total = self.quantityout + self.quantityin
    if self.quantityout > total * 0.6:
        return True
    else:
        return False

3. 补充补货提示输出

按照需求在循环中添加补货提示:

for item in shopping_list:
    print(item)
    print(f'\tUnit Price: ${item.calc_unit_price():.2f}')
    # 输出补货提示
    if item.order_note():
        print(f'\t⚠️ 需要补货')
    else:
        print(f'\t✅ 库存充足')
完整修复后的代码
class GroceryItem:
    def __init__(self, description, price, size, unit):
        self.description = description
        self.price = price
        self.size = size
        self.unit = unit
        
    def calc_unit_price(self):
        return self.price/self.size
    
    def __repr__(self):
        return f'{self.description}, {self.price}, {self.size}, {self.unit}'
    
    
class GroceryInventory(GroceryItem):
    def __init__ (self, description, price, size, unit, aisle, quantityout, quantityin):
        GroceryItem.__init__(self, description, price, size, unit)
        self.aisle = aisle
        # 将传入的字符串转为整数,避免数值计算错误
        self.quantityout = int(quantityout)
        self.quantityin = int(quantityin)
    
    def order_note(self):
        total = self.quantityout + self.quantityin
        if self.quantityout > total * 0.6:
            return True
        else:
            return False
        
    def __str__(self):
        return f'Item: {self.description} - ${self.price:.2f} for {self.size} {self.unit}\nAisle Number: {self.aisle}\nOn shelves: {self.quantityout}\nIn storage: {self.quantityin}'

# Test Drive:         
if __name__ == '__main__':
    carrots = GroceryInventory('carrots', 2.59, 1, 'pound', '12', '100', '600')
    donuts = GroceryInventory('glazed donuts', 4.95, 12, 'donuts', '12', '100', '600')
    olives = GroceryInventory('olives', 2.59, 6, 'ounces', '12', '100', '600')
    shopping_list = [carrots, donuts, olives]
    for item in shopping_list:
        print(item)
        print(f'\tUnit Price: ${item.calc_unit_price():.2f}')
        if item.order_note():
            print(f'\t⚠️ 需要补货')
        else:
            print(f'\t✅ 库存充足')
        print('-'*50)

额外说明:初始化quantityout和quantityin时,传入的是字符串类型,需转为整数才能正常进行数值计算,否则会触发字符串拼接逻辑,导致补货判断错误,修复代码中已添加类型转换。

内容的提问来源于stack exchange,提问作者Royal Yu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 16:25:23