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

WakeBdr bbull at optiosoftware.com
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():
                        try:
                                function._marked
                                print 'Class: %s' % cls
                                print 'Method: %s' % name
                                def toXML(self, *args, **kwargs):
                                        return
self._toXML(function(self, *args, **kwargs))
                                def toList(self, *args, **kwargs):
                                        return
self._toList(function(self, *args, **kwargs))
                                d[name+'XML'] = toXML
                                d[name+'List'] = toList
                        except AttributeError:
                                #traceback.print_exc()
                                pass
                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

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


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

===========OUTPUT=========
Class: <class '__main__.Magic'>
Method: printData
child-data
Traceback (most recent call last):
  File "test.py", line 43, in ?
    print t.printDataXML('data')
  File "test.py", 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