如何从对象中获取类的名称?

时间:2022-07-04 19:37:04

I have one function in my script where in the end I'm getting the class object. I want to return a class name from that function. What is the way to get classname from the respective class object?

我的脚本中有一个函数,最后我得到了类对象。我想从该函数返回一个类名。从相应的类对象获取classname的方法是什么?

3 个解决方案

#1


3  

Example:

例:

class MyClass:
    def whoami(self):
        return self.__class__.__name__

instance = MyClass()
print instance.whoami()  #<-- prints: MyClass

#2


2  

If your have an instance of the class, you can do:

如果你有一个类的实例,你可以这样做:

return obj.__class__.__name__

#3


2  

You can use __class__.__name__ in your object;

您可以在对象中使用__class __.__ name__;

print yourObject.__class__.__name__ 

Or this it not object its class, your can use this too;

或者它不反对它的类,你也可以使用它;

class myClass: # Create class
    pass

print myClass.__name__ # It will have 'myClass'

Regards,

问候,

#1


3  

Example:

例:

class MyClass:
    def whoami(self):
        return self.__class__.__name__

instance = MyClass()
print instance.whoami()  #<-- prints: MyClass

#2


2  

If your have an instance of the class, you can do:

如果你有一个类的实例,你可以这样做:

return obj.__class__.__name__

#3


2  

You can use __class__.__name__ in your object;

您可以在对象中使用__class __.__ name__;

print yourObject.__class__.__name__ 

Or this it not object its class, your can use this too;

或者它不反对它的类,你也可以使用它;

class myClass: # Create class
    pass

print myClass.__name__ # It will have 'myClass'

Regards,

问候,