回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>让我们想象一下,我使用了一个库,其源代码是按照以下形状编写的:</p>
<pre class="lang-py prettyprint-override"><code>class SuperLibraryDemo:
def __init__(self, test) -> None:
self.test = test
def demo(self) -> str:
return "Returning from demo method with name: %s" % self.test
class LibraryDemo(SuperLibraryDemo):
def __init__(self, test: str = "something") -> None:
super(LibraryDemo, self).__init__(test)
print("At LibraryDemo __init__ method: This should have been skipped")
def demo(self) -> None:
super().demo()
</code></pre>
<p>记住那是一个图书馆。我不应该根据自己的需要修改它的源代码。
但是,我需要切换<code>__init__</code>方法在<code>LibraryDemo</code>内调用的内部代码,原因超出了这个问题的范围</p>
<p>考虑到这个目标,我决定在元类的帮助下编写一个<code>CustomLibraryDemo</code>,如下所示:</p>
<pre class="lang-py prettyprint-override"><code>class MetaDemo(type):
def __new__(mcs, class_name: str, bases: Tuple[Type, ...], class_dict: Dict[str, Any]):
basis = bases[0]
c_attrs = dict(basis.__dict__)
prior_c_process_bases = basis.__base__
c_attrs["__init__"] = lambda self, settings: prior_c_process_bases.__init__(self, settings)
new_bases = types.new_class(basis.__qualname__, basis.__bases__,
exec_body=lambda np: MetaDemo.populate_class_dict(np, c_attrs))
return super(MetaDemo, mcs).__new__(mcs, class_name, (new_bases,), class_dict)
@staticmethod
def populate_class_dict(namespace: Dict[str, Any], attr: Dict[str, Any]) -> None:
for key, value in attr.items():
namespace[key] = value
class CustomLibraryDemo(LibraryDemo, metaclass=MetaDemo):
def __init__(self, test: Optional[str] = None) -> None:
super(CustomLibraryDemo, self).__init__(test)
print("At CustomDemo __init__ method: This message should appear")
def test(self) -> None:
print("In test method at CustomLibraryDemo class: %s" % self.test)
</code></pre>
<p>虽然这种方法乍一看似乎对我有效,但当我调用<code>CustomLibraryDemo().demo()</code>时,我得到一个错误,说:</p>
<pre class="lang-py prettyprint-override"><code>TypeError: super(type, obj): obj must be an instance or subtype of type
</code></pre>
<p>为什么</p>