从 Python 中的类中获取类名
使用类方法从类中获取类的名称。 类方法将类作为第一个参数传递,我们可以通过 cls.__name__ 访问类的名称。
class Employee():
@classmethod
def get_class_name(cls):
return cls.__name__
print(Employee.get_class_name()) # ?️ Employee
我们将 get_class_name 方法标记为类方法。 传递的第一个参数类方法是类。
__name__ 属性返回类的名称。
或者,我们可以使用 __qualname__ 属性。
class Employee():
class_name = __qualname__
@classmethod
def get_class_name(cls):
print(cls.class_name)
return cls.__name__
def example(self):
print(type(self).class_name)
print(Employee.get_class_name()) # ?️ Employee
emp1 = Employee()
emp1.example() # ?️ Employee
__qualname__
属性返回类的限定名称。
我们使用 type()
类来访问示例方法中的类。
type
类返回对象的类型。
最常见的返回值与访问对象的
__class__
属性相同。
在 self 对象上使用 __class__
属性将获得相同的结果。
def example(self):
print(self.__class__.class_name)
我们还可以通过类方法中的 __name__
属性访问类的名称。
class Employee():
@classmethod
def get_class_name(cls):
return cls.__name__
def example(self):
print(self.__class__.__name__)
print(Employee.get_class_name()) # 👉️ Employee
emp1 = Employee()
emp1.example() # 👉️ Employee
如果我们需要从类外部访问类的名称,也可以使用 __name__
属性。
class Employee():
def example(self):
print(self.__class__.__name__)
print(Employee.__name__) # 👉️ Employee
emp1 = Employee()
print(type(emp1).__name__) # 👉️ Employee
如果我们只能访问一个实例,请在访问 __name__
属性之前使用 type()
类。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。