我对 Python 还很陌生。最近在编写大量 PHP 时,我习惯了一些创造性地使用__get
和__set
“魔术”方法。这些仅在类的公共变量不存在时才被调用。
我试图在 Python 中复制相同的行为,但似乎失败得很惨。鉴于似乎没有办法以 C++/PHP 方式实际定义类变量,当我尝试在我的类中正常使用变量(即通过 self)时,它最终会调用__getattr__
!
如何定义我不想受到影响的类的属性__getattr__
?
下面是我想要做的一些示例代码,我想要self.Document
而self.Filename
不是调用__getattr__
.
谢谢您的帮助!
class ApplicationSettings(object):
RootXml = '<?xml version="1.0"?><Settings></Settings>'
def __init__(self):
self.Document = XmlDocument()
self.Document.LoadXml(RootXml)
def Load(self, filename):
self.Filename = filename
self.Document.Load(filename)
def Save(self, **kwargs):
# Check if the filename property is present
if 'filename' in kwargs:
self.Filename = kwargs['filename']
self.Document.Save(self.Filename)
def __getattr__(self, attr):
return self.Document.Item['Settings'][attr].InnerText
def __setattr__(self, attr, value):
if attr in self.Document.Item['Settings']:
# If the setting is already in the XML tree then simply change its value
self.Document.Item['Settings'][attr].InnerText = value
else:
# Setting is not in the XML tree, create a new element and add it
element = self.Document.CreateElement(attr)
element.InnerText = value
self.Document.Item['Settings'].AppendChild(element)