我试图从第三方包中包装一个类,这样我的新类看起来就像是第三方类的子类。第三方类不支持继承,它具有非常重要的功能,例如具有__getitem__
方法的函数。我可以使用基于Wrapping a class whose methods return instances of that class和How can I intercept calls to python's "magic" methods in new style classes?的解决方案来包装几乎所有属性和方法。但是,我仍然需要覆盖第三方类的__init__
方法。我怎样才能做到这一点?注意:我使用的是新式的课程。
代码:
import copy
class WrapperMetaclass(type):
"""
Works with the `Wrapper` class to create proxies for the wrapped object's magic methods.
"""
def __init__(cls, name, bases, dct):
def make_proxy(name):
def proxy(self, *args):
return getattr(self._obj, name)
return proxy
type.__init__(cls, name, bases, dct)
if cls.__wraps__:
ignore = set("__%s__" % n for n in cls.__ignore__.split())
for name in dir(cls.__wraps__):
if name.startswith("__"):
if name not in ignore and name not in dct:
setattr(cls, name, property(make_proxy(name)))
class Wrapper(object):
"""
Used to provide a (nearly) seamless inheritance-like interface for classes that do not support direct inheritance.
"""
__metaclass__ = WrapperMetaclass
__wraps__ = None
# note that the __init__ method will be ignored by WrapperMetaclass
__ignore__ = "class mro new init setattr getattr getattribute dict"
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):
if name is '_obj':
zot = 1
orig_attr = self._obj.__getattribute__(name)
if callable(orig_attr) and not hasattr(orig_attr, '__getitem__'):
def hooked(*args, **kwargs):
result = orig_attr(*args, **kwargs)
if result is self._obj:
return self
elif isinstance(result, self.__wraps__):
return self.__class__(result)
else:
return result
return hooked
else:
return orig_attr
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 ClassToWrap(object):
def __init__(self, data):
self.data = data
def theirfun(self):
new_obj = copy.deepcopy(self)
new_obj.data += 1
return new_obj
def __str__(self):
return str(self.data)
class Wrapped(Wrapper):
__wraps__ = ClassToWrap
def myfun(self):
new_obj = copy.deepcopy(self)
new_obj.data += 1
return new_obj
# can't instantiate Wrapped directly! This is the problem!
obj = ClassToWrap(0)
wr0 = Wrapped(obj)
print wr0
>> 0
print wr0.theirfun()
>> 1
这很有效,但对于真正无缝的继承行为,我需要直接实例化Wrapped
,例如
wr0 = Wrapped(0)
目前抛出
ValueError: wrapped object must be of <class '__main__.ClassToWrap'>
我尝试通过在__init__
中为WrapperMetaclass
定义新代理来覆盖,但很快就会遇到无限递归。
我的代码库对于不同技能级别的用户来说很复杂,因此我无法使用修补示例类ClassToWrap
或Wrapped
的定义的猴子修补程序或解决方案。我真的希望扩展上面的代码覆盖Wrapped.__init__
。
请注意,这个问题不仅仅是例如Can I exactly mimic inheritance behavior with delegation by composition in Python?。那篇文章没有任何答案,就像我在这里提供的那样详细。
答案 0 :(得分:1)
听起来你只是希望Wrapper.__init__
方法以不同的方式工作。它不是采用已经存在的__wraps__
类实例,而是应该采用其他类在其构造函数中期望的参数并为您构建实例。尝试这样的事情:
def __init__(self, *args, **kwargs):
if self.__wraps__ is None:
raise TypeError("base class Wrapper may not be instantiated")
else:
self._obj = self.__wraps__(*args, **kwargs)
如果您希望Wrapper
由于某种原因保持不变,则可以将逻辑放在新的Wrapped.__init__
方法中:
def __init__(self, data): # I'm explicitly naming the argument here, but you could use *args
super(self, Wrapped).__init__(self.__wraps__(data)) # and **kwargs to make it extensible