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

如何在Python中获取类内部方法返回的布尔值

问题原因

  • 你在__init__方法中调用self.check()时,没有将返回的布尔值存储为实例属性,返回值调用后直接被丢弃
  • 直接打印类实例默认输出的是实例的内存地址,无法直接拿到内部方法的返回值

解决方法

完全可以实现,不需要用到ctypes库,以下是三种常用实现方案:

方案1:将返回值保存为实例属性

在初始化时把check方法的返回值存到实例属性中,后续直接访问属性即可:

class Test:
    def __init__(self):
        self.value = 512
        # 存储返回值到实例属性
        self.check_result = self.check()

    def check(self):
        if self.value == 512:
            return True

address = Test()
print(address.check_result)

运行输出:True

方案2:实例化后手动调用方法拿返回值

不需要在初始化时提前调用,需要用到的时候手动调用check方法即可:

class Test:
    def __init__(self):
        self.value = 512

    def check(self):
        if self.value == 512:
            return True

address = Test()
print(address.check())

运行输出:True

方案3:重写__str__方法定制实例打印内容

如果需要直接打印类实例就输出布尔值,重写类的__str__魔术方法即可:

class Test:
    def __init__(self):
        self.value = 512

    def check(self):
        if self.value == 512:
            return True
    
    def __str__(self):
        return str(self.check())

address = Test()
print(address)

运行输出:True

内容的提问来源于stack exchange,提问作者Khalid Owl Walid

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 06:24:01