You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python attrs包定义的类中调用默认方法完成实例初始化

Hey there! Great question about using attrs—let me walk you through how to get that auto-set sum behavior working just like your vanilla Python class.

First, a quick note on your existing code: your get_sum and set_sum methods are missing the self parameter, which will throw errors when you try to call them. Plus, get_sum doesn’t have a return statement—without that, your set_sum would end up assigning None to sum! Those are easy fixes.

Now, for the attrs-specific solution: attrs provides a special hook called __attrs_post_init__ that runs automatically right after the generated __init__ method finishes setting up all your attributes. This is exactly where you want to call your set_sum method, just like you did in the __init__ of your vanilla class.

Here's the corrected, working version of your Calculator class:

from attrs import define, validators, field
from typing import Union

@define
class Calculator:
    var_1: float = field(validator=[validators.instance_of(float), validators.ge(0.)])
    var_2: float = field(validator=[validators.instance_of(float), validators.ge(0.)])
    sum: Union[float, None] = field(default=None, init=False)

    def get_sum(self):  # Added required self parameter
        return self.var_1 + self.var_2  # Added return statement

    def set_sum(self):  # Added required self parameter
        self.sum = self.get_sum()

    def __attrs_post_init__(self):
        # This runs immediately after instance initialization
        self.set_sum()

When you create a new Calculator instance, the __attrs_post_init__ method will automatically trigger set_sum, so your sum property gets populated right away:

calc = Calculator(2.5, 3.5)
print(calc.sum)  # Output: 6.0

As an extra tip: If you don’t need separate get_sum and set_sum methods long-term, you could even calculate sum directly in __attrs_post_init__ to keep things concise. But since you wanted to reuse your existing method structure, the above approach fits perfectly.

内容的提问来源于stack exchange,提问作者UGuntupalli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 11:09:10