Python – 如何定义不受__getattr__影响的属性?

我对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)

解决方法:

只有当Python无法在实例本身或其任何基类中找到该属性时,才会调用__getattr__.简单的解决方案是将Document和Filename添加到类中,以便找到它.

class ApplicationSettings(object):
    Document = None
    Filename = None
    RootXml = '<?xml version="1.0"?><Settings></Settings>'
    ...

相关文章

php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念