gpt4 book ai didi

python - 在实例化期间更改 __getattr__

转载 作者:太空宇宙 更新时间:2023-11-03 10:57:16 24 4
gpt4 key购买 nike

我想在类实例化期间更改 __getattr__。例如:

class AttrTest(object):
def __init__(self):
self.__getattr__ = self._getattr

def _getattr(self, attr):
print("Getting {}".format(attr))

我原以为这会像这样:

class AttrTest(object):
def __getattr__(self, attr):
print("Getting {}".format(attr))

但事实并非如此。

例如,当我运行时:

>>> at = AttrTest()
>>> at.test

我希望这两个类都打印Getting test,但是顶级类抛出一个AttributeError

__getattr__可以不这样改吗?

最佳答案

对于像 __getattr__ 这样的特殊方法,Python 在基 __dict__ 中搜索,而不是在实例 __dict__ 中搜索。

您可以在 special lookup 中阅读更多详细信息数据模型文档部分。

I have two implementations of __getattr__ that each use a different type of serialization (json, pickle), and I wanted my class to be able to select one based on a kwarg.

这不是覆盖 __getattr__ 的好用例。放弃这个想法,转而考虑使用@propertydescriptors动态处理您的序列化。

关于python - 在实例化期间更改 __getattr__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39379351/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com