formencode에는 classinstancemethod
데코레이터가 있으며 원하는 것을 수행합니다. 그것은 2 개 인자 (self
및 cls
, 그 중 하나가 호출 문맥에 따라 None
을 전달받을 수있다)
이 formencode/declarative.py
class 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 ('<bound class method %s.%s>'
% (self.type.__name__, self.func.func_name))
else:
return ('<bound method %s.%s of %r>'
% (self.type.__name__, self.func.func_name, self.obj))
샘플 사용에서 드러내을 가지고 방법을 필요로
class A(object):
data = 5
@classinstancemethod
def print_(self=None, cls=None):
ctx = self or cls
print ctx.data
>>> A.print_()
5
>>> a = A()
>>> a.data = 4
>>> a.print_()
4
시도해 보셨습니까? –
http://stackoverflow.com/questions/5812537/can-i-have-a-method-of-a-class-which-can-be-used-as-a-staticmethod-or-instance-me은 분명합니다. 재미있는. 나는 그것을하기의 적은 "해킹"방법이 있는지 다만 생각해보고 있었다 – xster