[英]asdict() inside .format() in a Python class
How can I use asdict()
method inside .format()
in oder to unpack the class attributes.如何在
.format()
中使用asdict()
方法来解压缩 class 属性。 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())
asdict
should be called on an instance of a class - self
, in this case.在这种情况下,应该在
asdict
- self
的实例上调用 asdict 。 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 --------------------^
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.