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)
__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)
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)
最后,如果您希望您的类具有不同的行为以转换为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)