I have an object subclass that I am using with a cusom repr() method.

class NewClass(object):
    def __repr__(self):
        return ', '.join('%s=%s'%(k, v) for (k,v) in self.__dict__.items())

This works fine (leaving out some more details about my program):

print test
a=1, b=2

But what I really want for reasons that aren't really worth getting into is for the class name to be printed out in the repr as well. For example,

print test
'NewClass: a=1, b=2'

But python objects don't have a name attribute. I'd prefer not making a separate attribute, aka:

class NewClass(object):
    def __repr__(self):
        return name+', '.join('%s=%s'%(k, v) for (k,v) in self.__dict__.items())

Is there a native way to do this?


>>> class NewClass(object):
    def __init__(self, **kwargs):

    def __repr__(self):
        return self.__class__.__name__ + ': '+ ', '.join('%s=%s'%(k, v) for (k,v) in self.__dict__.items())

>>> test=NewClass(a=1,b=2)
>>> test
NewClass: a=1, b=2
This question has already been answered. Start a new discussion instead.