python 2 中的 Monkey Patch 私有实例函数调用旧函数
Monkey Patch private instance function in python 2 with calling old function
我想猴子修补一个函数,该函数是私有的并且是 class 的一部分,但我也想调用修补后的函数。
示例:
class SomeClass:
def __some_function(self, foo):
return do_something()
现在我想写点像
def new_function(self, foo)
if foo == 'bar':
return True
return super(self).__some_function(foo)
SomeClass.__some_function = new_function
我试图用装饰器覆盖它,但我在调用旧函数时遇到问题,因为它不可访问。我还检查了模拟库,但不明白如何使用参数调用旧函数。
我试过的装饰器:
def patch_something(method):
def new_function(self, foo):
if foo == 'bar':
return True
return method(self, foo)
return new_function
SomeClass.__some_function = patch_something(SomeClass.__some_function)
我收到此错误(class 在另一个文件中 - 这是一个问题吗?)。
AttributeError: type object 'SomeClass' has no attribute '__some_function'
带有双下划线 __
的属性是名称损坏的,需要按照 the documentation:
中描述的损坏名称进行访问
Since there is a valid use-case for class-private members (namely to avoid name clashes of names with names defined by subclasses), there is limited support for such a mechanism, called name mangling. Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.
我想猴子修补一个函数,该函数是私有的并且是 class 的一部分,但我也想调用修补后的函数。
示例:
class SomeClass:
def __some_function(self, foo):
return do_something()
现在我想写点像
def new_function(self, foo)
if foo == 'bar':
return True
return super(self).__some_function(foo)
SomeClass.__some_function = new_function
我试图用装饰器覆盖它,但我在调用旧函数时遇到问题,因为它不可访问。我还检查了模拟库,但不明白如何使用参数调用旧函数。
我试过的装饰器:
def patch_something(method):
def new_function(self, foo):
if foo == 'bar':
return True
return method(self, foo)
return new_function
SomeClass.__some_function = patch_something(SomeClass.__some_function)
我收到此错误(class 在另一个文件中 - 这是一个问题吗?)。
AttributeError: type object 'SomeClass' has no attribute '__some_function'
带有双下划线 __
的属性是名称损坏的,需要按照 the documentation:
Since there is a valid use-case for class-private members (namely to avoid name clashes of names with names defined by subclasses), there is limited support for such a mechanism, called name mangling. Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.