어떻게 억제 할 classmethod를 얻을 수 있습니다

피터 :

나는, 즉, "랩"기존 classmethod에 노력하고있어

def Foo:
  @classmethod
  def bar(cls, x): return x + 2

old_bar = Foo.bar

def wrapped_bar(cls, x):
  result = old_bar(cls, x) # Results in an error
  return result

Foo.bar = wrapped_bar

그것은 그가 보인다 Foo.bar이미와 결합되어 cls = Foo, 어떻게 함수의 결합되지 않은 버전을받을 수 있나요 bar?

[I가 수정할 수 아니에요 Foo, 내가 패치있어 또 다른 코드베이스에 존재]

juanpa.arrivillaga :

당신이, 가정하자 :

>>> class Foo:
...     @classmethod
...     def bar(cls, x):
...         return x*42
...
>>> Foo.bar(2)
84

그리고 한 가지 방법은 직접 클래스의 이름 공간에 액세스 할 수 있습니다. 그런 다음에 액세스 할 수 있어야합니다 classmethod상기 사용할 수있는 장식 기능을 개체를하고 얻을 수 __func__속성 :

>>> vars(Foo)['bar']
<classmethod object at 0x103eec520>
>>> vars(Foo)['bar'].__func__
<function Foo.bar at 0x1043e49d0>

또는, 바운드 방식의 개체 자체에 액세스 할 수 있습니다 :

>>> bound = Foo.bar
>>> bound
<bound method Foo.bar of <class '__main__.Foo'>>
>>> bound.__func__
<function Foo.bar at 0x1043e49d0>

추천

출처http://43.154.161.224:23101/article/api/json?id=25749&siteId=1