You need to include z
as a variable when first defining the class but in addition you need to use field
to omit it from the __init__
list of parameters.
from dataclasses import dataclass, field, asdict
@dataclass
class A:
x: str
y: str
z: str = field(init=False)
def __post_init__(self):
self.z = self.x + self.y
a = A("abc", "def")
a.z
>> 'abcdef'
asdict(a)
>> {'x': 'abc', 'y': 'def', 'z': 'abcdef'}
You can see more here as shown in the docs.
This is because under the hood to create the dictionary, the asdict
method fetches the attributes from the __dataclass_fields__
attribute of the object. Since z
is not part of those attributes, it will not fetch z
when converting the object to a dictionary.