Python – 如何定义不受__getattr__影响的属性?
发布时间:2020-12-20 13:24:26 所属栏目:Python 来源:网络整理
导读:我对 Python很新.在最近编程很多PHP时,我习惯了一些创造性地使用__get和__set“魔术”方法.这些只在该类的公共变量不存在时才被调用. 我试图在Python中复制相同的行为,但似乎失败了.鉴于似乎没有办法以C / PHP方式实际定义类变量,当我尝试在我的类中通常使用
我对
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>' ... (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |