问题是Reclassing an instance in Python的扩展,其中OP很好地解释了这种情况(外来lib中的类,自己代码中的子类)。 但是,恕我直言的答案仍然有一些公开的细节:
lib_data = "baz"
class parent:
def __init__(self,foo,bar):
self._foo = foo
self._bar = bar
def do_things(self):
print(self._foo,self._bar)
def do_other_things(self,one2one_reference):
# this parent and the one2one_reference shall
# live in a 1:1 relationship
self._secret = one2one_reference # maybe ugly,but not in
# our hands to correct it
def some_lib_func():
p = parent("foo","bar")
p.do_other_things(lib_data)
return p
class child(foreign_lib.parent):
def do_things: # but differently!
print(42)
super().do_things()
# do_other_things() shall be inherited as is
def __init__(self,p):
# out of luck here, no copy-constructor for parent?
@classmethod
def convert_to_child(cls,a_parent):
a_parent.__class__ = cls
a_child = child(some_lib_func()) # will not work correctly
a_child = child.convert_to_child(some_lib_func()) # maybe this one?