Is there any method how to get class name inside a method in the same class? Or in general, if I have an instance of a class and I need to know which class is it instance of?
It's cls. __name__ . cls already points to the class, and now you're getting the name of its class (which is always type ). Follow this answer to receive notifications.
The simplest way is to call the getClass() method that returns the class's name or interface represented by an object that is not an array. We can also use getSimpleName() or getCanonicalName() , which returns the simple name (as in source code) and canonical name of the underlying class, respectively.
Get Class Name Using class. This is the most used way to get a class's name. In the following example, we have two classes: GetClassName with the main() method, and another class is ExampleClass . In the GetClassName class, we use ExampleClass.
In Qore (according to the tag on the question), you need to use the <object>::className() pseudo-method on your object.
ex:
prompt% qore -nX '(new Mutex()).className()'
"Mutex"
If you are in the class, use this pseudo-method on the automatic self
variable:
prompt% qore -ne '
class T {
string getClassName() {
return self.className();
}
}
class U inherits T {}
printf("%s\n", (new U()).getClassName());
'
U
Alternatively you can also use the get_class_name() function as in the following example:
prompt% qore -nX 'get_class_name(new Mutex())'
"Mutex"
Note that if a class defines a method with the same name as a pseudo-method, the class method will be called instead, and the pseudo-method cannot be called, in which case you have to use the function mentioned above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With