Reputation: 67
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())
Upvotes: 1
Views: 5214
Reputation: 1
You can also use **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(**asdict(self))
Upvotes: 0
Reputation: 311978
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 --------------------^
Upvotes: 3