2013-05-18 1 views
25

나는 다음과 같이 또 다른보다 일반적인 클래스 메소드를 사용하여 일부 클래스 메소드를 정의하기 위해 노력하고있어 : 그 방법 중 하나를 호출 할 때functools.partial는

class RGB(object): 
    def __init__(self, red, blue, green): 
     super(RGB, self).__init__() 
     self._red = red 
     self._blue = blue 
     self._green = green 

    def _color(self, type): 
     return getattr(self, type) 

    red = functools.partial(_color, type='_red') 
    blue = functools.partial(_color, type='_blue') 
    green = functools.partial(_color, type='_green') 

을하지만 내가 얻을 :

rgb = RGB(100, 192, 240) 
print rgb.red() 
TypeError: _color() takes exactly 2 arguments (1 given) 

rgb.red(rgb)이 작동하기 때문에 자체는 _color으로 전달되지 않습니다.

답변

30

메서드가 아닌 함수에서 부분을 만듭니다. functools.partial() 개체는 설명자가 아니며 자체적으로 self 인수를 추가하지 않으며 메서드 자체로 작동 할 수 없습니다. 랩된 바운드 메소드 또는 함수는 언 바운드 메소드로는 전혀 작동하지 않습니다. 이 documented입니다 :

partial 객체는이 호출 약한 referencable 점에서 function 객체처럼, 그리고 속성을 가질 수있다. 몇 가지 중요한 차이점이 있습니다. 예를 들어 __name____doc__ 속성은 자동으로 생성되지 않습니다. 또한 클래스에 정의 된 partial 개체는 정적 메서드처럼 동작하고 인스턴스 특성 조회 중에 바인딩 된 메서드로 변환되지 않습니다.

대신 property을 사용하십시오. 여기에 새로운 functools.partialmethod() object을 사용할 수 있습니다, 파이썬 3.4으로

class RGB(object): 
    def __init__(self, red, blue, green): 
     super(RGB, self).__init__() 
     self._red = red 
     self._blue = blue 
     self._green = green 

    def _color(self, type): 
     return getattr(self, type) 

    @property 
    def red(self): return self._color('_red') 
    @property 
    def blue(self): return self._color('_blue') 
    @property 
    def green(self): return self._color('_green') 

;이 설명입니다 이 인스턴스에 바인딩 옳은 일을 할 것입니다 :

class RGB(object): 
    def __init__(self, red, blue, green): 
     super(RGB, self).__init__() 
     self._red = red 
     self._blue = blue 
     self._green = green 

    def _color(self, type): 
     return getattr(self, type) 

    red = functools.partialmethod(_color, type='_red') 
    blue = functools.partialmethod(_color, type='_blue') 
    green = functools.partialmethod(_color, type='_green') 

을하지만 property 객체가 간단한 속성으로 사용할 수있는 반면, 호출 할 these'd 있습니다.

+0

알 수 있습니다. 감사. – Arjor

+1

'__init__'에서'self.red = functools.partial (RGB._color, self, 'red')'는 어떻게됩니까? Python2와도 호환됩니다. – dashesy

+2

@dashesy : 확실하지만 각 인스턴스 (메모리 비용)에 이러한 객체를 넣고 하위 클래스가이를 대체하기가 더 어려워집니다. –