More elegant to get a name: o.__class__.__name__

A

alf

Hi,
is there a more elegant way to get o.__class__.__name__. For instance I
would imagine name(o).
 
C

Carl Banks

alf said:
Hi,
is there a more elegant way to get o.__class__.__name__. For instance I
would imagine name(o).

def name_of_type(o):
return o.__class__.__name__

name_of_type(o)


Carl Banks

P.S. name(o) suggests it's the name of the object, not the type
P.P.S. you could use type(o).__name__ but it doesn't work for old-style
classes
 
G

George Sakkis

Carl said:
def name_of_type(o):
return o.__class__.__name__

name_of_type(o)


Carl Banks

P.S. name(o) suggests it's the name of the object, not the type
P.P.S. you could use type(o).__name__ but it doesn't work for old-style
classes

You mean it doesn't work for old-style instances; OTOH __class__
doesn't work for old style classes:AttributeError: class X has no attribute '__class__'

So to handle all cases, you'd have to go with:

def typename(o):
try: cls = o.__class__
except AttributeError: cls = type(o)
return cls.__name__
# or for fully qualified names
# return '%s.%s' % (cls.__module__, cls.__name__)

George
 
A

alf

alf said:
Hi,
is there a more elegant way to get o.__class__.__name__. For instance I
would imagine name(o).
decided to stick to o.__class__.__name__ for readibility.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top