Get Class Name in Python
To get the name of a class in Python access the __class__.__name__
property. To demonstrate this, let's initiate a simple class, create a new object using it then access the class name property.
Accessing Python Class Name Example
class foo:
def __init__(self, foo):
self.foo = foo
f = foo('hello')
print(f.__class__.__name__)
foo
You can also get the class from an object then access its name further in your program like this:
class foo:
def __init__(self, foo):
self.foo = foo
f = foo('hello')
c = f.__class__
print(c)
print(c.__name__)
<class '__main__.foo'>
foo
Access Object Class with type()
Another way to access the class name of an instantiated object is to use the __name__
property VIA the type()
function like this:
class foo:
def __init__(self, foo):
self.foo = foo
f = foo('hello')
print(type(f).__name__)
foo