How can I use asdict()
method inside .format()
in oder to unpack the class attributes.
So that instead of this:
JavaScript
x
12
12
1
from dataclasses import dataclass, asdict
2
3
@dataclass
4
class InfoMessage():
5
training_type: str
6
duration: float
7
distance: float
8
message = 'Training type: {}; Duration: {:.3f} ч.; Distance: {:.3f}'
9
10
def get_message(self) -> str:
11
return self.message.format(self.training_type, self.duration, self.distance)
12
I could write something like this:
JavaScript
1
10
10
1
@dataclass
2
class InfoMessage():
3
training_type: str
4
duration: float
5
distance: float
6
message = 'Training type: {}; Duration: {:.3f} ч.; Distance: {:.3f}'
7
8
def get_message(self) -> str:
9
return self.message.format(asdict().keys())
10
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:
JavaScript
1
4
1
def get_message(self) -> str:
2
return self.message.format(*asdict(self).values())
3
# Here --------------------^
4