本文介绍了一个类的定制双星运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何实现自定义双星运算符( **
)进行解包,类似于 __ iter __
单星运算符( *
)?
How does one implement custom double star operator (**
) for unpacking, similar to how __iter__
works with single star operator (*
)?
例如:
class PlayerManager(object):
def __init__(self, players=None):
self.players = players or []
# Made up method to support ** operator
def __dict_iter__(self):
for player in self.players:
yield get_steamid(player), player
def print_players(**players):
print(players)
player_manager = PlayerManager([list, of, players])
print_players(player_manager)
输出:
{
'STEAM_0:0:02201': <Player object at 0x0000000000>,
'STEAM_0:0:10232': <Player object at 0x0000000064>,
'STEAM_0:0:73602': <Player object at 0x0000000128>
}
推荐答案
映射。这里有一个例子:
As @ShadowRanger says, implement Mapping. Here's an example:
from collections.abc import Mapping
class Foo(Mapping):
def __iter__(self):
yield "a"
yield "b"
def __len__(self):
return 2
def __getitem__(self, item):
return ord(item)
f = Foo()
print(*f)
print(dict(**f))
程序输出:
a b
{'a': 97, 'b': 98}
这篇关于一个类的定制双星运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!