python - 包装一个 Python 对象

标签 python

我想将 Python 对象序列化为 plist 格式(这可以使用 pliSTLib 完成)。我的想法是编写一个包装其他对象的 PlistObject 类:

def __init__(self, anObject):
     self.theObject = anObject

并提供了一个“write”方法:

def write(self, pathOrFile):
    plistlib.writeToPlist(self.theObject.__dict__, pathOrFile)

现在,如果 PlistObject 的行为就像包装对象本身一样,那就太好了,这意味着所有属性和方法都以某种方式“转发”到包装对象。我意识到方法 __getattr____setattr__ 可以用于复杂的属性操作:

    def __getattr__(self, name):
         return self.theObject.__getattr__(name)

但是我当然遇到了构造函数现在产生无限递归的问题,因为 self.theObject = anObject 也尝试访问包装的对象。

我怎样才能避免这种情况?如果整个想法看起来很糟糕,也请告诉我。

最佳答案

除非我遗漏了什么,否则它会工作得很好:

def __getattr__(self, name):
    return getattr(self.theObject, name)

编辑:对于那些认为查找 self.theObject 会导致对 __getattr__ 的无限递归调用的人,让我告诉你:

>>> class Test:
...     a = "a"
...     def __init__(self):
...         self.b = "b"
...     def __getattr__(self, name):
...         return 'Custom: %s' % name
... 
>>> Test.a
'a'
>>> Test().a
'a'
>>> Test().b
'b'
>>> Test().c
'Custom: c'

__getattr__ 仅作为 last 调用resort .由于可以在 __dict__ 中找到 theObject,因此不会出现任何问题。

关于python - 包装一个 Python 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/884594/

相关文章:

python - 如何在python中使用比较和 ' if not'?

python - 函数和列表

python - 使用正则表达式删除包含数字的双引号

python - pip 未使用 pip.conf 中定义的额外索引 url

python - Spark ml 中 ALS 的意外关键字参数 'coldStartStrategy'

python - 谷歌应用引擎 : JSON module

python - pandas dataframe之间的计算返回NaN

python - 如何从flask-SQLAlchemy 查询SQL View

Python:AttributeError: 'Point'对象没有属性 'x'

python - 如何使用 Python 抓取实时流数据?