파이썬에서 관련 메소드 데코레이터의 패밀리를 만드는 법을 배우기 위해 나는 좋은 파이썬의 방법을 생각하는 데 어려움을 겪고있다.파이썬에서 서브 클래 싱 메소드 데코레이터
서로 일치하지 않는 목표는 데코 레이팅 된 메서드가 바인딩 된 인스턴스의 데코레이터 특성과 특성에 모두 액세스 할 수 있기를 원한다는 것 같습니다. 여기에 내가의 의미는 다음과 같습니다
는from functools import wraps
class AbstractDecorator(object):
"""
This seems like the more natural way, but won't work
because the instance to which the wrapped function
is attached will never be in scope.
"""
def __new__(cls,f,*args,**kwargs):
return wraps(f)(object.__new__(cls,*args,**kwargs))
def __init__(decorator_self, f):
decorator_self.f = f
decorator_self.punctuation = "..."
def __call__(decorator_self, *args, **kwargs):
decorator_self.very_important_prep()
return decorator_self.f(decorator_self, *args, **kwargs)
class SillyDecorator(AbstractDecorator):
def very_important_prep(decorator_self):
print "My apartment was infested with koalas%s"%(decorator_self.punctuation)
class UsefulObject(object):
def __init__(useful_object_self, noun):
useful_object_self.noun = noun
@SillyDecorator
def red(useful_object_self):
print "red %s"%(useful_object_self.noun)
if __name__ == "__main__":
u = UsefulObject("balloons")
u.red()
물론 물론 항상이 작업을 얻을 수있는 방법이 있다는 것을
My apartment was infested with koalas...
AttributeError: 'SillyDecorator' object has no attribute 'noun'
주를 생산한다. 예를 들어, 충분한 인수를 가진 팩토리를 사용하면 SillyDecorator의 일부 생성 된 인스턴스에 메소드를 연결할 수 있습니다. 그러나 상속으로이를 수행 할 수있는 합리적인 방법이 있는지 궁금해합니다.
대단하군요! 나는 기술자들에 대해 머리 글자를 더 잘 감쌀 필요가 있다고 생각한다. 데코레이터 제작자에 관해서는 : 그렇습니다. 그것이 제가 끝내 준 것입니다. 문제는 제가 인수로 전달한 것이 함수라는 것입니다. 데코레이터의 각 버전마다 여러 함수 정의가있었습니다. 그래서 최상위 레벨에 정의 된 생성자 메서드 정의를 공급하고 내가 논리적으로 매우 많은 상속을 받았을 때 생성자에 연결하는 해킹을 느꼈습니다. –