Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get just a class name without module, etc [duplicate]

Tags:

python

I'm probably overlooking something simple. Given an instance of a class, I'd like to get just the class name. For example:

class Foooo: pass
instance = Foooo()

print("instance.__class__ = "+str(instance.__class__))
print("Just the class name: "+str(instance.__class__).split(".")[-1][:-2])

This gives the following output:

instance.__class__ = <class '__main__.Foooo'>
Just the class name: Foooo

Is there something simpler than

str(instance.__class__).split(".")[-1][:-2]?

I'm in Python 3.2 if that helps...

like image 728
Matthew Lund Avatar asked Dec 02 '11 20:12

Matthew Lund


People also ask

What is __ class __ in Python?

__class__ is an attribute on the object that refers to the class from which the object was created. a. __class__ # Output: <class 'int'> b. __class__ # Output: <class 'float'> After simple data types, let's now understand the type function and __class__ attribute with the help of a user-defined class, Human .

How do you return a class name in Python?

The first and easiest method to get a class name in python is by using __class__ property which basically refers to the class of the object we wish to retrieve. Here we combine the property with __name__ property to identify the class name of the object or instance.

How do you return a class name in Java?

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.

How do you print a class type in Python?

How to Print the Type of a Variable in Python. To get the type of a variable in Python, you can use the built-in type() function. In Python, everything is an object. So, when you use the type() function to print the type of the value stored in a variable to the console, it returns the class type of the object.


1 Answers

Try this:

instance.__class__.__name__
like image 50
Andrew Clark Avatar answered Oct 09 '22 08:10

Andrew Clark