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

Python调用add_product()出现TypeError:缺少4个必要位置参数求助

解决TypeError问题的方案

错误原因

  1. 调用p.add_product()时未传入方法要求的4个必填参数:product_name、product_type、available_quantity、unit_price,而Products类的add_product方法明确要求这四个参数。
  2. 错误实例化抽象类Products()来调用方法,实际应使用已创建的ProductsImplementation实例products——这才是实现了业务逻辑的子类实例,Products本身仅定义抽象方法,无实际功能。
  3. 输入的available_quantity和unit_price是字符串类型,直接传入可能导致后续模型操作出错,需转换为对应数值类型。

修复步骤

  • 删除p = Products()代码,改用已创建的products实例调用add_product
  • 调用add_product时传入收集到的四个参数,同时将available_quantity转为整数,unit_price转为浮点数
  • 修正输入提示的拼写错误:avilable quantity改为available quantity

修改后的完整Driver.py代码

from Abstractions.Products import Products
from itertools import product
from Implementation.ProductsImplementation import ProductsImplementation
from Implementation.VendorImplementation import VendorImplementation
from Models.VendorSessionModel import VendorSessionModel

if __name__ == '__main__':
    vendor = VendorImplementation()
    username = input("Enter vendor name:")
    password = input("Enter your password:")
    login_res = vendor.login(username, password)
    
    if login_res == False:
        print("Not authorized Vendor")
    else:
        products = ProductsImplementation(username)
        print("Enter Number of product you want to add:")
        n = int(input())
        
        for i in range(1, n+1):
            product_name = input("Please Enter Product Name:")
            product_type = input("Please Enter product type:")
            available_quantity = int(input("Please enter available quantity:"))
            unit_price = float(input("please enter unit price:"))
            
            products.add_product(product_name, product_type, available_quantity, unit_price)

额外说明

  • Products作为抽象基类仅定义规范,实际业务逻辑由子类ProductsImplementation实现,不要直接实例化抽象类调用方法。
  • 转换输入数值类型是为了匹配后续ProductModel.add_product的参数类型要求,避免类型不兼容问题。

内容的提问来源于stack exchange,提问作者sagar patel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 17:06:56