擅长:python、mysql、java
<p>您可以使用<code>**kwargs</code>让您的<code>__init__</code>接受任意数量的关键字参数(“kwargs”表示“关键字参数”),并丢弃不必要的参数:</p>
<pre><code>class NewsItem(NamedTuple):
id: str
title: str
content: str
service: str
published_at: datetime
@classmethod
def from_payload(cls, id=None, title=None, content=None, service=None, published_at=None, **kwargs) -> 'NewsItem':
return cls(id, title, content, service, published_at)
</code></pre>
<p>具有自省<code>NamedTuple</code>类属性的替代解决方案(参见@MOROZILnic answer+comment)</p>