Hi,

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):

test=NewClass(a=1,b=2)
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):
    name='NewClass'
    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?

Thanks

>>> class NewClass(object):
    def __init__(self, **kwargs):
        self.__dict__.update(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

Edited 4 Years Ago by pyTony

Thanks. I had tried this already and must have had a typo or something!

Edited 4 Years Ago by hughesadam_87

This question has already been answered. Start a new discussion instead.