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

如何在Python 3.11中获取函数所属类的名称

解决方案

方法一:使用实例方法

给方法添加self参数,通过self.__class__.__name__获取类名:

class Test:
    def test69(self):
        print(self.__class__.__name__)

# 调用示例
obj = Test()
obj.test69()  # 输出: Test

方法二:使用类方法

用@classmethod装饰器,方法参数改为cls,直接通过cls.__name__获取类名,这种方式无需实例化就能调用:

class Test:
    @classmethod
    def test69(cls):
        print(cls.__name__)

# 调用示例
Test.test69()  # 输出: Test
obj = Test()
obj.test69()  # 同样输出: Test

原代码的问题

  • 方法未定义self或cls参数,Python会自动把调用时的实例/类作为第一个参数传入,会触发参数不匹配的报错。
  • 代码里的classname是未定义的变量,Python无法识别该名称。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 20:45:53