如何在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
相关产品推荐
相关产品推荐

