Skip to main content
 首页 » 编程设计

python之包装一个类,其方法返回该类的实例

2024年10月01日8me-sa

我需要编写一个类来包装来自第三方包的类。通常,第三方类具有返回第三方类实例的方法。这些方法的包装版本必须将这些实例转换为包装类的实例,但我无法让它工作。我正在使用带有新型类的 Python 2.7。

基于 Create a wrapper class to call a pre and post function around existing functions? , 我有以下内容。

import copy 
 
class Wrapper(object): 
    __wraps__  = None 
 
    def __init__(self, obj): 
        if self.__wraps__ is None: 
            raise TypeError("base class Wrapper may not be instantiated") 
        elif isinstance(obj, self.__wraps__): 
            self._obj = obj 
        else: 
            raise ValueError("wrapped object must be of %s" % self.__wraps__) 
 
    def __getattr__(self, name): 
        orig_attr = self._obj.__getattribute__(name) 
        if callable(orig_attr): 
            def hooked(*args, **kwargs): 
                result = orig_attr(*args, **kwargs) 
                if result == self._obj: 
                    return result 
                return self.__class__(result) 
            return hooked 
        else: 
            return orig_attr 
 
class ClassToWrap(object): 
    def __init__(self, data): 
        self.data = data 
 
    def theirfun(self): 
        new_obj = copy.deepcopy(self) 
        new_obj.data += 1 
        return new_obj 
 
class Wrapped(Wrapper): 
    __wraps__ = ClassToWrap 
 
    def myfun(self): 
        new_obj = copy.deepcopy(self) 
        new_obj.data += 1 
        return new_obj 
 
obj = ClassToWrap(0) 
wr0 = Wrapped(obj) 
print wr0.data 
>> 0 
wr1 = wr0.theirfun() 
print wr1.data 
>> 1 
wr2 = wr1.myfun() 
print wr2.data 
>> 2 
wr3 = wr2.theirfun() 
print wr3.data 
>> 2 

现在为什么 theirfun() 第一次工作,但第二次就不行? wr0 和 wr2 都是 Wrapped 类型,调用 wr2.theirfun() 不会引发错误,但不会添加1 到 wr2.data 符合预期。

抱歉,我不正在寻找以下替代方法:

  1. 猴子补丁。我的代码库很重要,我不知道如何确保补丁将通过 import 语句的网络传播。
  2. 为每个第三方包的所有这些棘手方法编写单独的包装器方法。他们太多了。

ETA:有几个有用的答案引用了 Wrapper 类之外的基础 _obj 属性。但是,这种方法的重点是可扩展性,因此此功能需要位于 Wrapper 类中。 myfun 需要在其定义中不引用 _obj 的情况下按预期运行。

请您参考如下方法:

问题在于您在 Wrapped 类中实现了 myfun。您只更新类实例的 data 成员,但包装类的成员(ClassToWrap 实例即 _obj)data 成员已过时,使用的是上一次调用 theirfun 的值。

您需要在两个实例之间同步数据值:

class Wrapper(object): 
    ... 
    def __setattr__(self, attr, val): 
        object.__setattr__(self, attr, val) 
        if getattr(self._obj, attr, self._obj) is not self._obj: # update _obj's member if it exists 
            setattr(self._obj, attr, getattr(self, attr)) 
 
 
class Wrapped(Wrapper): 
    ... 
    def myfun(self): 
        new_obj = copy.deepcopy(self) 
        new_obj.data += 1 
        return new_obj 
 
obj = ClassToWrap(0) 
wr0 = Wrapped(obj) 
print wr0.data 
# 0 
wr1 = wr0.theirfun() 
print wr1.data 
# 1 
wr2 = wr1.myfun() 
print wr2.data 
# 2 
wr3 = wr2.theirfun() 
print wr3.data 
# 3 
wr4 = wr3.myfun() 
print wr4.data 
# 4 
wr5 = wr4.theirfun() 
print wr5.data 
# 5