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?


Recommended Answers

All 2 Replies

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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.