wordpress做阿里巴巴国际站,传智播客,phpcms获取网站名称,百度上线wordpress结构化数据插件我一直在深入研究Python类中的运算符重载和特殊方法,并且我注意到许多内置函数具有等效的特殊方法名称#xff1a; int(x)调用x .__ int __() next(x)在Python 2中调用x .__ next __()或x.next()但是,一些函数,即tuple()和dict(),没有任何等价物.我知道对于这种特殊方…我一直在深入研究Python类中的运算符重载和特殊方法,并且我注意到许多内置函数具有等效的特殊方法名称 int(x)调用x .__ int __() next(x)在Python 2中调用x .__ next __()或x.next()但是,一些函数,即tuple()和dict(),没有任何等价物.我知道对于这种特殊方法尚未出现这种需要,但在某些情况下,调用类的dict()转换方法可能很有用.我该如何实现呢或者,对于试图使用这种逻辑的人,您会怎么说# I think this is quite interesting, so I shall post my own implementation of it as well解决方法:选项1__iter__转换为元组或字典,或任何采用迭代的类型,都依赖于__iter__方法.class ListOfKeys():def __init__(self, lst):self.lst lstdef __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键和__getitem__或者,要转换为dict,您可以实现两个键和__getitem__.class ListOfKeys():def __init__(self, lst):self.lst lstdef keys(self):yield from self.lstdef __getitem__(self, item):return Nonelok ListOfKeys([1, 2, 3])d dict(lok)print(d) # {1: None, 2: None, 3: None}选项3两者都支持多种类型最后,如果您希望您的类具有不同的行为以转换为dict和元组,则以下示例演示dict将优先考虑键和__getitem__解决方案.class Foo:def __iter__(self):yield 1def keys(self):yield 2def __getitem__(self, item):return 3print(dict(Foo())) # {2: 3}print(tuple(Foo())) # (1,)标签python,python-3-x,class,function,oop来源 https://codeday.me/bug/20190828/1746542.html