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

Python3:如何向类A方法传入类B未实例化的方法?

问题与解决方案

原始代码与需求

用户的代码如下:

class A:
    def Amethod(self, method):
        b = B()
        b.method()

class B:
    def Bmethod(self):
        print('Hello')

需求是调用A类的Amethod时,传入B类的Bmethod作为参数,但直接写a.Amethod(Bmethod)会报错——因为Bmethod是B的实例方法,需要绑定到B实例才能调用,而B的实例是在Amethod内部创建的。


可行实现方式

方式一:传入方法名称字符串

修改Amethod,通过getattr从B实例中获取对应方法并调用:

class A:
    def Amethod(self, method_name):
        b = B()
        getattr(b, method_name)()

class B:
    def Bmethod(self):
        print('Hello')

# 调用示例
a = A()
a.Amethod("Bmethod")

方式二:传入类的未绑定方法

直接传入B.Bmethod,在Amethod里手动将方法绑定到B实例:

class A:
    def Amethod(self, method):
        b = B()
        method(b)

class B:
    def Bmethod(self):
        print('Hello')

# 调用示例
a = A()
a.Amethod(B.Bmethod)

方式三:使用functools.partial适配复杂场景

如果后续需要传递带参数的方法,这种方式更灵活:

from functools import partial

class A:
    def Amethod(self, func):
        b = B()
        func(b)

class B:
    def Bmethod(self):
        print('Hello')
    def BmethodWithParam(self, msg):
        print(msg)

# 调用示例
a = A()
# 无参数方法
a.Amethod(partial(B.Bmethod))
# 带参数方法
a.Amethod(partial(B.BmethodWithParam, msg="Hi there"))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 23:32:37