我想用我的python静态方法添加装饰器,如下所示:
class AdminPanelModel(db.Model):
id = db.Column('id', db.Integer, primary_key=True)
visible = db.Column(db.Boolean,)
def decor_init(func):
def func_wrapper(*kargs, **kwargs):
for l in model.all(): #internal logic
pass
return func(*kargs, **kwargs)
return func_wrapper
@staticmethod
@decor_init
def all_newscollection_at_adminpanel():
pass
我尝试将@staticmethod
添加到我的装饰器中并尝试按照func(AdminPanelModel,*kargs, **kwargs)
进行函数调用,但没有运气,仍然坚持以下错误消息:
TypeError: unbound method func_wrapper() must be called with AdminPanelModel instance as first argument (got nothing instead)
有什么办法可以实现吗?我知道可以通过其他方式做同样的工作,但更多的是教育问题,而不是以某种方式完成工作。
答案 0 :(得分:2)
您需要使用classmethod
代替:
@classmethod
@decor_init
def all_newscollection_at_adminpanel(cls):
pass
调用是相同的,但classmethod
隐式接收该类作为第一个参数,然后它也将被传递到修饰函数
看到差异:
class AdminPanelModel(object):
def decor_init(func):
def func_wrapper(*kargs, **kwargs):
print kargs # The first element should be of type class AdminPanelModel
return func(*kargs, **kwargs)
return func_wrapper
@staticmethod
@decor_init
def staticm():
pass
@classmethod
@decor_init
def classm(cls):
pass
他们屈服
AdminPanelModel.staticm()
>>> () # empty, which is reason for error
AdminPanelModel.classm()
>>> (<class '__main__.AdminPanelModel'>,) # class instance as first parameter