私はPythonにかなり慣れていません。__get
最近、多くの PHP をプログラミングする中で、__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)