简体   繁体   English

Class 装饰器与 class 方法

[英]Class decorator with class methods

I have written a class decorator that monkey-patches a class overwriting the init and adding a method persist ().我已经编写了一个 class 装饰器,它猴子修补了 class 覆盖init并添加了一个方法 persist ()。 So far everything OK.到目前为止一切正常。

Now I need to add a class method (static method) to the decorated class.现在我需要在装饰的 class 中添加一个 class 方法(静态方法)。 What do I have to change in my code to make staticMethod() a static method of the decorated class?我必须在我的代码中进行哪些更改才能使 staticMethod() 成为修饰的 class 的 static 方法?

This is my code:这是我的代码:

#! /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 ()

And the output is: output 是:

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)
    @staticmethod
    def staticMethod (): print "I am static"

or或者

    def staticMethod (): print "I am static"
    cls.staticMethod = staticmethod(staticMethod)

use the @staticmethod decorator.使用 @staticmethod 装饰器。

@staticmethod
def staticMethod() : ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM