How to subclass a frozen dataclass
I have inherited the Customer
dataclass. This identifies a customer in the customer DB table.
Customer
is used to produce summary statistics for transactions pertaining to a given customer. It is hashable, hence frozen.
I require a SpecialCustomer
(a subclass of Customer
) it has an extra property: special_property
. Most of the properties inherited from Customer
will be set to fixed values. This customer does not exist in the Customer table.
I wish to utilise code which has been written for Customer
. Without special_property
we will not be able to distinguish between special customers.
How do I instantiate SpecialCustomer
?
Here is what I have. I know why this doesn't work. Is there some way to do this?:
from dataclasses import dataclass
@dataclass(frozen=True, order=True)
class Customer:
property: str
@dataclass(frozen=True, order=True)
class SpecialCustomer(Customer):
special_property: str = Field(init=False)
def __init__(self, special_property):
super().__init__(property="dummy_value")
self.special_property = special_property
s = SpecialCustomer(special_property="foo")
Error:
E dataclasses.FrozenInstanceError: cannot assign to field 'special_property'
<string>:4: FrozenInstanceError
Comments
Post a Comment