动漫人物
选项1: __iter__强制转换为tuple或dict,或采用可迭代的任何类型,都依赖于此__iter__方法。class ListOfKeys(): def __init__(self, lst): self.lst = lst def __iter__(self): for k in self.lst: yield (k, None)lok = ListOfKeys([1, 2, 3])d = dict(lok)print(d) # {1: None, 2: None, 3: None}同样适用于元组。t = tuple(lok)print(t) # ((1, None), (2, None), (3, None))选项2:keys和__getitem__另外,要强制转换为a dict,您可以同时实现keys和__getitem__。class ListOfKeys(): def __init__(self, lst): self.lst = lst def keys(self): yield from self.lst def __getitem__(self, item): return Nonelok = ListOfKeys([1, 2, 3])d = dict(lok)print(d) # {1: None, 2: None, 3: None}选项3:两者都支持多种类型最后,如果您希望您的类对adict和a进行强制转换具有不同的行为tuple,下面的示例演示了dict优先于keysand__getitem__解决方案的问题。class Foo: def __iter__(self): yield 1 def keys(self): yield 2 def __getitem__(self, item): return 3print(dict(Foo())) # {2: 3}print(tuple(Foo())) # (1,)