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

如何在Python类的方法中正确打印类名?

如何在Python中打印对象的类名

当你直接打印self时,Python会调用对象的默认__str__方法,输出的是包含内存地址的对象信息,而非类名。要正确输出类名,有两种简单常用的方式:

  • 使用*self.__class__.__name__*:__class__属性指向当前对象所属的类,__name__属性存储类的名称字符串
  • 使用*type(self).__name__*:type()函数返回对象的类型(即所属类),再通过__name__获取类名

修改你的代码如下(以self.__class__.__name__为例):

from abc import ABC, abstractmethod

class Clothing(ABC):
    @abstractmethod
    def desc(self):
        pass


class Shirt(Clothing):
    def desc(self):
        x = input('Enter a color: ')
        y = input('Enter the size: ')

        # 替换{self}为{self.__class__.__name__}获取类名
        print(f"Your {self.__class__.__name__} is: {x}\nAnd its size is: {y}")


class Jean(Shirt):
    def desc(self):
        super().desc()


jean = Jean()
jean.desc()

运行后会得到符合预期的输出:

Enter a color: red
Enter the size: 32
Your Jean is: red
And its size is: 32

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 08:56:08