How can I use asdict() method inside .format() in oder to unpack the class attributes.
So that instead of this:
from dataclasses import dataclass, asdict
@dataclass
class InfoMessage():
training_type: str
duration: float
distance: float
message = 'Training type: {}; Duration: {:.3f} ч.; Distance: {:.3f}'
def get_message(self) -> str:
return self.message.format(self.training_type, self.duration, self.distance)
I could write something like this:
@dataclass
class InfoMessage():
training_type: str
duration: float
distance: float
message = 'Training type: {}; Duration: {:.3f} ч.; Distance: {:.3f}'
def get_message(self) -> str:
return self.message.format(asdict().keys())
Advertisement
Answer
asdict should be called on an instance of a class – self, in this case. Additionally, you don’t need the dict’s keys, you need its values, which you can spread using the * operator:
def get_message(self) -> str:
return self.message.format(*asdict(self).values())
# Here --------------------^