Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 具有类方法的类装饰器_Python_Decorator - Fatal编程技术网

Python 具有类方法的类装饰器

Python 具有类方法的类装饰器,python,decorator,Python,Decorator,我已经编写了一个类装饰器,monkey对一个类进行了修补,覆盖了init,并添加了一个persist()方法。到目前为止一切正常 现在我需要向修饰类添加一个类方法(静态方法)。要使staticMethod()成为修饰类的静态方法,我需要在代码中做哪些更改 这是我的代码: #! /usr/bin/env python # -*- coding: utf-8 -*- class Persistent (object): def __init__ (self, table = None, r

我已经编写了一个类装饰器,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 ()
输出为:

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)

插入tblPerson
(colage,colname)
价值观(23,无名氏)
回溯(最近一次呼叫最后一次):
文件“/w2.py”,第39行,在
试验方法()
TypeError:必须使用测试实例作为第一个参数调用未绑定的方法staticMethod()(而不是获取任何内容)


使用@staticmethoddecorator

@staticmethod
def staticMethod() : ...

非常感谢。有时它很简单,Python有时有奇怪的语法。
    def staticMethod (): print "I am static"
    cls.staticMethod = staticmethod(staticMethod)
@staticmethod
def staticMethod() : ...