【问题标题】:How to override getattr or getattribute in python to call gettattr or getattribute inside itself as in lazy recursive directory listing如何在 python 中覆盖 getattr 或 getattribute 以在其内部调用 gettattr 或 getattribute,如在惰性递归目录列表中一样
【发布时间】:2020-07-24 17:52:12
【问题描述】:

例如这样的:

class DotTabLoader():
    def __init__(self, basedir, loaderfun):
        self._basedir = pathlib.PosixPath(basedir)
        self._loaderfun = loaderfun
        self._list = list(self._basedir.glob('*/'))
        self._names = [x.name.split('=')[1] for x in self._list]
        self._names_dict = dict(zip(self._names, range(self._names)))
    def __dir__(self):
        return self._names
    def __getattribute__(self, name):
        # how to access self._list etc here?
        return super().__getattribute__(name)
    

无限递归会出错。

更新:

正确的做法是这样的:

class DotTabLoader():
    def __init__(self, basedir, loaderfun):
        self._basedir = pathlib.PosixPath(basedir)
        self._loaderfun = loaderfun
        self._list = list(self._basedir.glob('*/'))
        self._names = [x.name.split('=')[1] for x in self._list]
        self._names_dict = dict(zip(self._names, range(len(self._names))))
    def __dir__(self):
        return self._names + super().__dir__()
    def __getattr__(self, name):
        try:
            ind = self._names_dict[name]
            basedir = self._list[ind]
            return DotTabLoader(basedir, self._loaderfun)
        except KeyError as e:
            return super().__getattribute__(name)

【问题讨论】:

    标签: python setattr


    【解决方案1】:

    最简单的方法是实现__getattr__,它仅在正常查找失败时调用。这意味着您可以访问 __getattr__ 实现中的普通属性,而无需执行任何特殊操作,并且不会因为基类查找成功而递归调用它。

        def __getattr__(self, name):
            return self._list[0]  # works fine!
    

    __getattribute__ 更像是一种特殊情况,因为它是无条件调用的,而不是作为正常查找的后备。根据文档 (https://docs.python.org/3/reference/datamodel.html#object.getattribute) 如果你想访问__getattribute__ 中的属性而不调用你自己重写的__getattribute__ 实现,你需要调用object 实现:

        def __getattribute__(self, name):
            return object.__getattribute__(self, '_list')[0]
    

    【讨论】:

    • 是的,过去有很多搜索噪音。我以前什至做过,但找不到。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    • 1970-01-01
    • 2013-08-15
    • 2017-08-13
    • 2010-12-31
    • 2014-10-14
    相关资源
    最近更新 更多