我正在尋找適當的解決方案,我已經做了這段代碼。我只想在打印XML時打印我的XML。在Python中動態覆蓋魔術方法
from xml.dom.minidom import Document, DOMImplementation
class MyClass(object):
init():
pass
def create_xml():
doc = Document()
# I know i cannot do that, I know. I need proper solution for that
doc.__str__ = self.print_doc
def print_doc(document):
return document.toprettyxml(encoding='UTF-8')
我們能夠找出它一個不乾淨的方式,這樣的作品,所以你可以看到我的想法在這裏:
from xml.dom.minidom import Document, DOMImplementation
def create_xml():
doc = Document()
document.__str__ = partial(self.print_doc, document=document)
def print_doc(document):
return document.toprettyxml(encoding='UTF-8')
我的類需要是靜態的,因爲軟件無法處理在整個運行過程中,比一個實例更多,仍然需要用戶在運行期間創建多個xml(是的,這是搞砸了,但我無法幫助)。 而不是讓奇怪的事情,我做了不便,會爲我工作:
class Child(Document):
def __str__(self):
return document.toprettyxml(encoding='UTF-8')
...所以這個類可以讓我打印
class MyClass(object):
def create_xml():
return Document()
......所有這一切,東陽我必須有
def main():
xml = MyClass.create()
print(xml)
...而不是僅僅
xml = Document()
對不起大家了混亂...我想刨這裏是我搞砸了第一
你只想做你寫什麼,因爲'self'不存在那裏。試試'doc .__ str__ = print_doc'。 – jonrsharpe
您涉嫌工作的代碼不是用戶友好的,因爲它實際上並不工作,但除此之外,我不明白爲什麼您說它不是人性化的。 – Goyo