Can I use decorators to manipulate return type or create methods?

WakeBdr bbull at
Fri Oct 20 15:45:24 CEST 2006

OK, I think I'm close now.  I just can't get past this one error.  Here
is my code, followed by the output produced when I run it.

class Magic(type):
        def __new__(cls, name, bases, d):
                for name, function in d.items():
                                print 'Class: %s' % cls
                                print 'Method: %s' % name
                                def toXML(self, *args, **kwargs):
self._toXML(function(self, *args, **kwargs))
                                def toList(self, *args, **kwargs):
self._toList(function(self, *args, **kwargs))
                                d[name+'XML'] = toXML
                                d[name+'List'] = toList
                        except AttributeError:
                return type(name, bases, d)

def mark(f):
        f._marked = True
        return f

class test(object):

        def _toXML(self, value):
                return '<xml>%s</xml>' % value
        def _toList(self, value):
                return '<list>%s</list>' % value

class testtest(test):

        __metaclass__ = Magic

        def printData(self, data):
                return 'child-%s' % data

t = testtest()
print t.printData('data')
print t.printDataXML('data')
print t.printDataList('data')

Class: <class '__main__.Magic'>
Method: printData
Traceback (most recent call last):
  File "", line 43, in ?
    print t.printDataXML('data')
  File "", line 11, in toXML
    return self._toXML(function(self, *args, **kwargs))
TypeError: __new__() takes exactly 4 arguments (3 given)

Diez B. Roggisch wrote:
> WakeBdr schrieb:
> > Diez,
> > I get what that accomplishes now, but I'm having problems in my
> > implementation.  I was able to write a standalone class that worked
> > correctly.  However, in my code the class that I need to exhibit this
> > functionality inherits from another class.  This seems to cause
> > problems when I attempt to implement you solution.
> You need to give a __metaclass__ to one of them, and I think they must
> be new-style-classes.
> Diez

More information about the Python-list mailing list