如何在 Python 中包装对象?(或者是猴子补丁?)
发布时间:2022-05-27 09:55:34 231
相关标签: # node.js
我正在使用 python-docx 来自动化我的工作。我正在尝试创建自己的类,包装 docx.document.Document 类,因此我有一个对象可以继承父类的所有内容,但也允许我在其中编写自定义函数。这是我对如何使其工作的猜测:
class WrappedDoc(docx.document.Document):
def __new__(cls, _docx=None):
doc = docx.Document(_docx)
return doc
def test(self):
return 1
doc = WrappedDoc()
print(doc.test())
它不会打印1的结果,我想这是意料之中的,因为doc只是一个未包装的对象。但我该怎么做呢?
编辑:找到解决方案。我想我包装错了。我找到的解决方案使用getattr。
class WrappedDoc(docx.document.Document):
def __init__(self, docx_=None):
self._doc = docx.Document(docx_)
def __getattr__(self, __name: str) -> Any:
return self._doc.__getattribute__(__name)
def test(self):
return 1
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报