【问题标题】:Class decorator with class methods带有类方法的类装饰器
【发布时间】:2011-06-01 02:43:21
【问题描述】:

我编写了一个类装饰器,它对覆盖 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)

【问题讨论】:

    标签: python decorator


    【解决方案1】:
        @staticmethod
        def staticMethod (): print "I am static"
    

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

    【讨论】:

    • 谢谢。有时候就是这么简单。
    • Python 有时语法很奇怪。
    【解决方案2】:

    使用@staticmethod 装饰器。

    @staticmethod
    def staticMethod() : ...
    

    【讨论】:

      猜你喜欢
      • 2014-01-14
      • 2023-03-29
      • 1970-01-01
      • 2020-01-11
      • 2012-07-31
      • 1970-01-01
      相关资源
      最近更新 更多