0

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'.

1
  • 1
    Please explain why classobj is not a good type name for an old-style class, and why you need to change that. Note that for new-style classes ("class bob(object):") the type name is type. Commented Dec 4, 2009 at 23:18

2 Answers 2

14

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.

Sign up to request clarification or add additional context in comments.

Comments

12
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.

3 Comments

Brilliant, if very very horrifying, answer to a strange question.
@eblume: Not completely crazy. Perhaps the OP was creating a function that constructed classes. I suppose that would be called a meta-factory, since a factory constructs instances. Some enum implementations, for example, might want a unique class name for each enum type, so that enum('Days', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun') returns an instance of a new class Days, with members Mon, Tue, Wed, Thu, Fri, Sat, Sun.
@Deep in that case you're probably best off calling the 3 arg version of type directly. Modifying __class__ is still evil.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.