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

Python类中调用其他方法时如何获取实际返回值而非绑定对象

问题解决:获取方法返回值而非绑定对象

你当前的问题出在get_all_values方法里——直接将方法名放入列表时,只是引用了方法的绑定对象,并没有执行方法来获取返回值。只需给每个方法名加上()调用方法,就能拿到实际返回值。

修改后的get_all_values方法

def get_all_values(self):
    values_list = [self.get_input_cable(), self.get_output_cable(), self.get_color(), self.get_price()]
    return values_list

原因说明

写self.get_input_cable时,Python会把它识别为一个方法对象(也就是你看到的<bound method...>格式内容),不会执行方法逻辑。只有加上(),才会触发方法执行,返回你需要的属性值。

修改后运行结果

调用C1.get_all_values()会输出:

['C type', 'B type', 'Black', 600]

额外优化提示

如果你的getter方法只是单纯返回属性值,完全可以直接访问实例属性,省去额外的getter方法,代码会更简洁:

def get_all_values(self):
    values_list = [self.input_cable, self.output_cable, self.color, self.price]
    return values_list

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 19:05:21