用于字典转换的特殊方法名称的内置函数

N C*_*han 3 python oop class function python-3.x

我一直在深入研究Python类中的运算符重载和特殊方法,并且我注意到许多内置函数具有等效的特殊方法名称:

  • int(x) 电话 x.__int__()
  • next(x)调用x.__next__()x.next()Python 2

但是,有几个功能,即tuple()dict(),没有任何等价物.我知道对于这种特殊方法还没有出现这种需要,但在某些情况下,dict()在类上调用转换的方法可能是有用的.我该如何实现呢?或者,对于试图使用这种逻辑的人,您会怎么说?

# I think this is quite interesting, so I shall post my own implementation of it as well
Run Code Online (Sandbox Code Playgroud)

Oli*_*çon 5

选项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}
Run Code Online (Sandbox Code Playgroud)

这同样适用于元组.

t = tuple(lok)

print(t) # ((1, None), (2, None), (3, None))
Run Code Online (Sandbox Code Playgroud)

选项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 None

lok = ListOfKeys([1, 2, 3])
d = dict(lok)

print(d) # {1: None, 2: None, 3: None}
Run Code Online (Sandbox Code Playgroud)

选项3:两者都支持多种类型

最后,如果您希望您的类具有不同的行为以转换为a dict和a tuple,则以下示例演示dict将优先考虑keys__getitem__解决方案.

class Foo:
    def __iter__(self):
        yield 1

    def keys(self):
        yield 2

    def __getitem__(self, item):
        return 3

print(dict(Foo())) # {2: 3}
print(tuple(Foo())) # (1,)
Run Code Online (Sandbox Code Playgroud)

  • 确切地说`__iter__`或`__getitem__`. (3认同)