【问题标题】:Python attrs validator and __attrs_post_init__() are not calledPython attrs 验证器和 __attrs_post_init__() 未被调用
【发布时间】:2021-03-25 16:47:38
【问题描述】:

我使用@attr.s 创建了一个类,并定义了一个属性验证器和 attrs_post_init() 方法。我希望在实例化此类的对象时自动调用这些方法。但是这些似乎根本不会在 init() 之前或之后的任何时间被调用。

import attr
from typeguard import typechecked
from typing import Any, Optional

@attr.s(auto_attribs=True, init=False)
class Entry:
    name: Optional[str] = attr.ib()

    @typechecked
    def __init__(
        self, name: Optional[str] = None
    ):
        print("Entered init")
        self.name = name

    @name.validator
    def name_validator(self, _attribute: Any, value: Optional[str]) -> None:
        print("Entered validator")

    def __attrs_post_init__(self) -> None:
        print("Entered post")
        
Entry("Bob")

这只会打印Entered init

什么时候调用属性验证器和 attrs_post_init() 方法?

【问题讨论】:

    标签: python attr


    【解决方案1】:

    attrs 不能在对象构造时执行工作,除非您让它处理对象构造。您期望发生的事情通常会在生成的 __init__ 方法中发生,但您将其关闭。

    通过拒绝生成的__init__ 并实施您自己的,已对这些任务负责。如果您想要验证,需要这样做。如果你想调用__attrs_post_init__需要调用它。

    【讨论】:

      猜你喜欢
      • 2018-07-25
      • 1970-01-01
      • 2018-03-25
      • 2015-01-02
      • 2021-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-29
      相关资源
      最近更新 更多