Декоратор класса с методами класса - PullRequest
2 голосов
/ 01 июня 2011

Я написал декоратор класса, который исправляет класс, перезаписывая init и добавляя метод persist ().Пока все в порядке.

Теперь мне нужно добавить метод класса (статический метод) к оформленному классу.Что мне нужно изменить в моем коде, чтобы сделать staticMethod () статическим методом декорированного класса?

Это мой код:

#! /usr/bin/env python
# -*- coding: utf-8 -*-

class Persistent (object):
    def __init__ (self, table = None, rmap = None):
        self.table = table
        self.rmap = rmap

    def __call__ (self, cls):
        cls.table = self.table
        cls.rmap = self.rmap
        oinit = cls.__init__
        def finit (self, *args, **kwargs):
            print "wrapped ctor"
            oinit (self, *args, **kwargs)
        def persist (self):
            print "insert into %s" % self.table
            pairs = []
            for k, v in self.rmap.items (): pairs.append ( (v, getattr (self, k) ) )
            print "(%s)" % ", ".join (zip (*pairs) [0] )
            print "values (%s)" % ", ".join (zip (*pairs) [1] )
        def staticMethod (): print "I am static"
        cls.staticMethod = staticMethod
        cls.__init__ = finit
        cls.persist = persist
        return cls

@Persistent (table = "tblPerson", rmap = {"name": "colname", "age": "colage"} )
class Test (object):
    def __init__ (self, name, age):
        self.name = name
        self.age = age

a = Test ('John Doe', '23')
a.persist ()
Test.staticMethod ()

И вывод:

wrapped ctor
insert into tblPerson
(colage, colname)
values (23, John Doe)
Traceback (most recent call last):
  File "./w2.py", line 39, in <module>
    Test.staticMethod ()
TypeError: unbound method staticMethod() must be called with Test instance as first argument (got nothing instead)

Ответы [ 2 ]

3 голосов
/ 01 июня 2011
    @staticmethod
    def staticMethod (): print "I am static"

или

    def staticMethod (): print "I am static"
    cls.staticMethod = staticmethod(staticMethod)
1 голос
/ 01 июня 2011

используйте декоратор @staticmethod.

@staticmethod
def staticMethod() : ...
...