我正在使用一个包,该包为我提供了一个对象,其中填充了一堆数据,我不想费心手动序列化这些数据并用于初始化另一个对象。我想要做的是为我自己的目的附加一堆额外的方法到对象上。
理想情况下,我想神奇地子类化一个实例,但这似乎不可能。 Monkey-patching 可能会“起作用”,但互联网上说它不是很好的形式,而且因为我代码的其他部分实际上可能在其他地方使用 native 类,所以看起来很危险。
我尝试创建一个包装器对象,但是很多(全部?)the magic methods (e.g. __iter__
) skip the __getattribute__
call ,所以不完整。打一堆传递函数定义(例如 def __iter__(self): return iter(object.__getattribute__(self, '_digraph'))
)看起来很笨重(我可能会忘记一个) .
class ColliderGraph(object):
def __init__(self, digraph):
self._digraph = digraph
def __getattribute__(self, name):
cls_attrs = ['_digraph', 'whereis', 'copy'] # more to follow.
if name not in cls_attrs:
return object.__getattribute__(
object.__getattribute__(self, '_digraph'), name)
else:
return object.__getattribute__(self, name)
#return getattr(self._digraph, name)
def whereis(self, node):
"""find a node inside other nodes of the digraph"""
def copy(self):
return ColliderGraph(self._digraph.copy())
我在其他地方以更有限的方式开始 patch the instance像这样的单个奇数函数:
def _whereis_addon(digraph, node):
"""For patching onto specially-modifed digraph objects."""
# then elsewhere...
digraph.whereis = types.MethodType(_whereis_addon, digraph)
但是如果 .copy()
被调用然后它失去升级(我想我也可以修补它......),并且以这种方式添加一堆方法也看起来很丑陋,但也许可行。
有没有更好的出路?
最佳答案
首先,我认为最明智的选择是修补 digraph
实例以添加您需要的方法,并在其中修补 __copy__
,或者甚至坚持使用您的包装器,并使用元类为魔术方法添加代理,如 this answer 中所建议到您链接到的问题。
就是说,我最近在考虑“神奇地”子类化一个实例的想法,并认为我会与您分享我的发现,因为您正在考虑同样的事情。这是我想出的代码:
def retype_instance(recvinst, sendtype, metaklass=type):
""" Turn recvinst into an instance of sendtype.
Given an instance (recvinst) of some class, turn that instance
into an instance of class `sendtype`, which inherits from
type(recvinst). The output instance will still retain all
the instance methods and attributes it started with, however.
For example:
Input:
type(recvinst) == Connection
sendtype == AioConnection
metaklass == CoroBuilder (metaclass used for creating AioConnection)
Output:
recvinst.__class__ == AioConnection
recvinst.__bases__ == bases_of_AioConnection +
Connection + bases_of_Connection
"""
# Bases of our new instance's class should be all the current
# bases, all of sendtype's bases, and the current type of the
# instance. The set->tuple conversion is done to remove duplicates
# (this is required for Python 3.x).
bases = tuple(set((type(recvinst),) + type(recvinst).__bases__ +
sendtype.__bases__))
# We change __class__ on the instance to a new type,
# which should match sendtype in every where, except it adds
# the bases of recvinst (and type(recvinst)) to its bases.
recvinst.__class__ = metaklass(sendtype.__name__, bases, {})
# This doesn't work because of http://bugs.python.org/issue672115
#sendtype.__bases__ = bases
#recv_inst.__class__ = sendtype
# Now copy the dict of sendtype to the new type.
dct = sendtype.__dict__
for objname in dct:
if not objname.startswith('__'):
setattr(type(recvinst), objname, dct[objname])
return recvinst
思路是重新定义实例的__class__
,将其变为我们选择的新类,并将__class__
的原始值添加到 inst.__bases__
(连同新类型的 __bases__
)。此外,我们将新类型的 __dict__
复制到实例中。这听起来相当疯狂而且可能确实如此,但在我对它进行的少量测试中,它似乎(大部分)确实有效:
class MagicThread(object):
def magic_method(self):
print("This method is magic")
t = Thread()
m = retype_instance(t, MagicThread)
print m.__class__
print type(m)
print type(m).__mro__
print isinstance(m, Thread)
print dir(m)
m.magic_method()
print t.is_alive()
print t.name
print isinstance(m, MagicThread)
输出:
<class '__main__.MagicThread'>
<class '__main__.MagicThread'>
(<class '__main__.MagicThread'>, <class 'threading.Thread'>, <class 'threading._Verbose'>, <type 'object'>)
True
['_Thread__args', '_Thread__block', '_Thread__bootstrap', '_Thread__bootstrap_inner', '_Thread__daemonic', '_Thread__delete', '_Thread__exc_clear', '_Thread__exc_info', '_Thread__ident', '_Thread__initialized', '_Thread__kwargs', '_Thread__name', '_Thread__started', '_Thread__stderr', '_Thread__stop', '_Thread__stopped', '_Thread__target', '_Verbose__verbose', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_block', '_note', '_reset_internal_locks', '_set_daemon', '_set_ident', 'daemon', 'getName', 'ident', 'isAlive', 'isDaemon', 'is_alive', 'join', 'magic_method', 'name', 'run', 'setDaemon', 'setName', 'start']
This method is magic
False
Thread-1
False
除了最后一行 - isinstance(m, MagicThread)
是 False
之外,所有输出都完全符合我们的要求。这是因为我们实际上并没有将 __class__
分配给我们定义的 MagicMethod
类。相反,我们创建了一个具有相同名称和所有相同方法/属性的单独类。理想情况下,这可以通过在 retype_instance
中实际重新定义 MagicThread
的 __bases__
来解决,但 Python 不允许这样做:
TypeError: __bases__ assignment: 'Thread' deallocator differs from 'object'
这似乎是一个 bug in Python一直追溯到 2003 年。它还没有被修复,可能是因为在实例上动态重新定义 __bases__
是一个奇怪的而且可能是个坏主意!
现在,如果您不关心能否使用 isinstance(obj, ColliderGraph)
,以上内容可能适合您。或者它可能会以奇怪的、意想不到的方式失败。我真的不建议在任何生产代码中使用它,但我想我会分享它。
关于python - 向现有类实例添加方法,或如何将实例添加到 "subclass",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25394550/