tags:

views:

142

answers:

2

How would you change a class type name to something other than classobj?

class bob():
    pass

foo = bob
print "%s" % type(foo).__name__

which gets me 'classobj'.

+9  A: 

In your example, you've defined foo as a reference to the class definition of bob, not to an instance of bob. The type of an (old-style) class is indeed classobj.

If you instantiate bob, on the other hand, the result will be different:

# example using new-style classes, which are recommended over old-style
class bob(object):
    pass

foo = bob()
print type(foo).__name__
'bob'

If you just want to see the name of the bob type without instantiating it, use:

print bob.__name__
'bob'

This works because bob is already a class type, and therefore has a __name__ property that you can query.

Jarret Hardie
Thanks for the help!
Duck
+2  A: 
class DifferentTypeName(type): pass

class bob:
  __metaclass__ = DifferentTypeName

foo = bob
print "%s" % type(foo).__name__

emits DifferentTypeName, as you require. It seems unlikely that this is actually what you want (or need), but, hey, it is the way to do exactly what you so explicitly ask for: change a class's type's name. Assigning a suitable renamed derivative of type to foo.__class__ or bob.__class__ later would also work, so you could encapsulate this into a pretty peculiar function:

def changeClassTypeName(theclass, thename):
  theclass.__class__ = type(thename, (type,), {})

changeClassTypeName(bob, 'whatEver')

foo = bob
print "%s" % type(foo).__name__

this emits whatEver.

Alex Martelli