问题是在 Python 中重新分类实例的扩展,其中 OP 很好地解释了这种情况(外部库中的类,自己代码中的子类)。但是,恕我直言,答案中仍有一些未解决的细节:
- 如果我将父对象重新分类为子对象,那么拥有子构造函数是否有效?毕竟,由于没有复制构造函数(以及所有深拷贝和浅拷贝的问题),我不能期望正确构造完整的父对象(即使我知道父构造函数签名,请参阅 self._secret在示例中)。锁定子构造函数是否明智(例如通过在那里抛出异常)?
- C++ 如何处理这种情况(继承)?
- 我用代码打破了各种 OOP 原则吗?这是对某些设计模式的一记耳光吗?基本的想法是,根据我的需要改造一个对象的一些小细节,毕竟看起来并不那么有罪。
foreign_lib.py:
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
我的代码.py:
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?