我是 Python 的新手。最近在大量 PHP 编程中,我习惯了一些创造性地使用 __get
和 __set
“魔术”方法。这些仅在类的公共(public)变量不存在时调用。
我试图在 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)
最佳答案
__getattr__
仅在 Python 无法在实例本身或其任何基类中找到属性时调用。简单的解决方案是将 Document
和 Filename
添加到类中以便找到它。
class ApplicationSettings(object):
Document = None
Filename = None
RootXml = '<?xml version="1.0"?><Settings></Settings>'
...
关于Python - 如何定义不受 __getattr__ 影响的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7115531/