Since the above dataclass would be initiated as:
class B:
def __init__(self, x: ObjectId = ObjectId()):
self.id=x
The default value for the class would always be the static ObjectId
generated when the class is loaded.
In the end, I suppose dynamic values should not be passed as init params.
The correct way would be to use __post_init__
:
from dataclasses import field
@dataclass
class B:
id: ObjectId = field(init=False)
def __post_init__(self):
self.id = ObjectId()
b =B()
b.id
>>ObjectId('60104262ee527a385cb44a11')
c =B()
c.id
>>ObjectId('6010426bee527a385cb44a12')
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…