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

Recommended Answers

All 2 Replies

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

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, networking, learning, and sharing knowledge.