formencode有一个classinstancemethod修饰符,它可以做您想要的。它要求该方法有2个参数(self和cls,其中一个可以根据调用上下文被传递None)
来自formencode/declarative.pyclass classinstancemethod(object):
"""
Acts like a class method when called from a class, like an
instance method when called by an instance. The method should
take two arguments, 'self' and 'cls'; one of these will be None
depending on how the method was called.
"""
def __init__(self, func):
self.func = func
def __get__(self, obj, type=None):
return _methodwrapper(self.func, obj=obj, type=type)
class _methodwrapper(object):
def __init__(self, func, obj, type):
self.func = func
self.obj = obj
self.type = type
def __call__(self, *args, **kw):
assert not kw.has_key('self') and not kw.has_key('cls'), (
"You cannot use 'self' or 'cls' arguments to a "
"classinstancemethod")
return self.func(*((self.obj, self.type) + args), **kw)
def __repr__(self):
if self.obj is None:
return (''
% (self.type.__name__, self.func.func_name))
else:
return (''
% (self.type.__name__, self.func.func_name, self.obj))
示例用法
^{pr2}$