gpt4 book ai didi

python - 带有类方法的类装饰器

转载 作者:行者123 更新时间:2023-11-28 23:05:25 25 4
gpt4 key购买 nike

我写了一个类装饰器,它猴子修补了一个类,覆盖了 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)

最佳答案

    @staticmethod
def staticMethod (): print "I am static"

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

关于python - 带有类方法的类装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6195698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com