1. 程式人生 > 其它 >Python獲取類名的字串格式

Python獲取類名的字串格式

技術標籤:Python基礎知識pythonclassstring

某些時候需要將類名轉字串類引用,則需要使用以下方法:

__class__.__name__
  1. 自身使用
class MyClass(object):
    def class_name_str(self):
        print(f'1. 將自身類名轉字串:{self.__class__.__name__}')


a = MyClass()
a.class_name_str()
print(f'2. 外部引用類名字串:{a.__class__.__name__}')

輸出結果為:

1. 將自身類名轉字串:MyClass
2
. 外部引用類名字串:MyClass