使用类方法的类装饰器

2024-10-17 08:25:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个类修饰符,monkey修补了一个类,覆盖了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 ()

输出是:

^{pr2}$

Tags: 方法代码nametestselfageinitdef