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

Python中能否将类/对象作为函数参数?兼析传参报错问题

Python类实例方法参数错误及类类型参数标注方案

问题背景

你希望在Python中给函数参数指定类/对象类型,同时遇到了实例方法调用的参数错误:明明只传了2个参数,却报错TypeError: sum_stores() takes 2 positional arguments but 3 were given。测试代码如下:

class Store:
    def calc_cost(rate: float, qty: int) -> float:
        return rate * qty
    
def sum_stores(store1, total):
    total += store1.calc_cost(15, 30)

total = 0

ice_cream_shop = Store()
sum_stores(ice_cream_shop, total)

错误原因

报错的核心不是函数参数的类型标注问题,而是类的实例方法定义不符合Python规则:

  • Python中,类的实例方法必须将self作为第一个参数(参数名可自定义,但行业通用self),它用来接收调用该方法的实例对象本身。
  • 当你执行store1.calc_cost(15, 30)时,Python会自动把store1作为第一个参数传入calc_cost,此时实际传入的参数是(store1, 15, 30),但你定义的calc_cost只接受rate和qty两个参数,导致参数数量不匹配,触发报错。

解决方法

先修正类的实例方法,添加self参数,同时注意不可变类型的赋值逻辑:

class Store:
    # 实例方法添加self作为第一个参数
    def calc_cost(self, rate: float, qty: int) -> float:
        return rate * qty
    
def sum_stores(store1, total):
    total += store1.calc_cost(15, 30)
    return total  # 整数是不可变类型,需返回新值才会生效

total = 0
ice_cream_shop = Store()
total = sum_stores(ice_cream_shop, total)
print(total)  # 输出450

正确实现类/对象作为函数参数的类型标注

如果要指定函数参数的类类型,直接用类名作为类型注解即可,示例如下:

class Store:
    def calc_cost(self, rate: float, qty: int) -> float:
        return rate * qty

# 指定store1的类型为Store类的实例,total为int类型
def sum_stores(store1: Store, total: int) -> int:
    total += store1.calc_cost(15, 30)
    return total

total = 0
ice_cream_shop = Store()
total = sum_stores(ice_cream_shop, total)

这样既明确了参数的类型,能让IDE提供代码提示,同时符合Python的类型标注规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 06:55:02