您可以在标签中将self.__class__.__name__作为属性返回class Super:
@property
def label(self):
return self.__class__.__name__
class Sub(Super):
pass
print Sub().label
或者您可以在__init__方法中设置它
^{pr2}$
这显然只适用于实例化的类
要访问类方法中的类名,只需在cls上调用__name__class XYZ:
@classmethod
def my_label(cls):
return cls.__name__
print XYZ.my_label()class classproperty(object):
def __init__(self, fget):
self.fget = fget
def __get__(self, owner_self, owner_cls):
return self.fget(owner_cls)
class Super(object):
@classproperty
def label(cls):
return cls.__name__
class Sub(Super):
pass
print Sub.label #works on class
print Sub().label #also works on an instance
class Sub2(Sub):
@classmethod
def some_classmethod(cls):
print cls.label
Sub2.some_classmethod()