将 attr.asdict() 过滤器与可调用对象一起使用

Using attr.asdict() filter with a callable

我正在尝试在我的 class 上创建一个方法,它将 return 只有 public 属性作为字典。我在语法上苦苦挣扎。这是我尝试失败的方法:

@attr.s
class C:
    x = attr.ib()
    _y = attr.ib()

    def _no_privates(a, _):
       return not a.name.startswith("_")

    def public_properties_to_dict(self):
       return attr.asdict(self, filter=attr.filters.include(_no_privates))

在你的例子中,_no_privates不是函数而是方法。

我认为更好的解决方案是将 _no_privates 从 class 移到顶部范围。它是一个函数,它接受一个参数和 returns 一个基于该参数的值,仅此而已。

如果硬要让_no_privates成为方法,可以写成filter=attr.filters.include(self._no_privates).

然而 _not_privates 的签名在任何情况下都是错误的。如果它是一个函数,它应该a。如果是方法,第一个参数是self,后面是a.