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

如何用另一类的方法正确覆写类方法?解决TypeError报错

问题:如何用另一个类的方法覆写第一个类的方法?

以下是编写的Python代码:

class SomeClass:
    def __init__(self) -> None:
        pass

    def some_class_function(self, par):
        print(par)

class SomeOtherClass:
    def __init__(self) -> None:
        pass

    def some_other_class_function(self, par):
        print(par+1)

if __name__ == "__main__":
    sc = SomeClass()
    sc.some_class_function = SomeOtherClass.some_other_class_function
    sc.some_class_function(1)

执行后出现报错:

TypeError: some_other_class_function() missing 1 required positional argument: 'par'

报错原因

直接赋值SomeOtherClass.some_other_class_function时,这是一个未绑定的类方法,它需要接收两个参数:self和par。调用sc.some_class_function(1)时,Python仅传入了1,此时1会被当作self参数,导致par缺失,从而触发错误。

正确解决方法

方法1:绑定另一个类的实例方法

创建SomeOtherClass的实例,将其绑定后的方法赋值给目标实例:

if __name__ == "__main__":
    sc = SomeClass()
    soc = SomeOtherClass()
    # 赋值绑定后的方法,自动将soc作为self参数
    sc.some_class_function = soc.some_other_class_function
    sc.some_class_function(1)  # 输出:2

方法2:用functools.partial手动绑定self参数

如果不需要创建SomeOtherClass的实例,可以借助functools.partial将目标实例绑定为方法的self参数:

import functools

if __name__ == "__main__":
    sc = SomeClass()
    # 将sc绑定为some_other_class_function的self参数
    sc.some_class_function = functools.partial(SomeOtherClass.some_other_class_function, sc)
    sc.some_class_function(1)  # 输出:2

方法3:覆写整个类的方法(所有实例生效)

如果希望SomeClass的所有实例都使用新方法,直接修改类的方法属性即可:

if __name__ == "__main__":
    # 修改类的方法,所有新创建的SomeClass实例都会使用该方法
    SomeClass.some_class_function = SomeOtherClass.some_other_class_function
    sc = SomeClass()
    sc.some_class_function(1)  # 输出:2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 13:55:17