如何在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

