获取实例的类名的Python程序
在本文中,我们将了解如何访问Python实例的类名。
基础班
Python3
# this is a class named car
class car:
def parts():
pass
c = car()
# this prints the class of a c
# this is a class of a c which is
# variable containing a class
print(c.__class__)
# this prints the name of the class
classes = c.__class__
print(classes.__name__)
Python3
# this is a class named car
class car:
def parts():
pass
c = car()
# this prints the class of a c
print(type(c).__name__)
Python3
# class for getting the class name
class test:
@property
def cls(self):
return type(self).__name__
a = test()
print(a.cls)
输出:
car
此外,我们还可以打印 c 的类型(汽车类),它给出了 c 的对象,而 __name__ 提供了类的名称。
Python3
# this is a class named car
class car:
def parts():
pass
c = car()
# this prints the class of a c
print(type(c).__name__)
输出:
car
返回类名的函数
Python3
# class for getting the class name
class test:
@property
def cls(self):
return type(self).__name__
a = test()
print(a.cls)
在这里,我们使用了@property 装饰器来获取除Python方法之外的名称。要获取有关 @property 装饰器的更多信息,请参阅Python属性装饰器。
输出:
test