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

Python调用classmethod未执行仅返回绑定方法该如何解决?

Python classmethod 代码修改方案

你当前的代码存在3处需要修正的点:

  • @classmethod 修饰的类方法,必须默认接收第一个参数,行业约定命名为cls,指代当前类本身
  • 类属性a不能直接在方法内通过变量名a访问,需要通过cls参数调用
  • 调用类方法时末尾缺少括号(),原写法仅获取方法对象本身,不会执行方法内的打印逻辑

修改后的可运行代码如下:

class Test:
    a = 'inside method'
    @classmethod
    def testclass_method(cls):
        print(cls.a)
# 调用类方法
Test.testclass_method()

运行上述代码即可正常输出inside method。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 18:36:03