我对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>'
...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。