gpt4 book ai didi

python - 为什么 `*args` 的值很奇怪?

转载 作者:太空狗 更新时间:2023-10-30 01:57:45 24 4
gpt4 key购买 nike

这是我的代码快照:

class C(dict):
def __init__(*args, **kwds):
print 'args = {}'.format(args)
print 'kwds = {}'.format(kwds)
if not args:
raise TypeError("descriptor '__init__' of 'Counter' object needs an argument")

self = args[0]

args = args[1:]

if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))

super(C, self).__init__()


if __name__ == '__main__':
c = C()

当我运行这段代码时,我对输出感到困惑:

C:\Users\elqstux\Desktop>python wy.py
args = ({},)
kwds = {}

对于 c = C(),我认为代码会引发错误,因为在这种情况下 args 将是 (),但是从输出来看,args({},),这是什么原因?

self, args = args[0], args[1:] # 允许传递“self”关键字

最佳答案

*args({},) 因为您没有显式声明 self 参数。因此,当调用 __init__ 时,self 参数最终成为 args 中的第一个元素。由于您继承自 dict,因此您获得了 dictrepr,即 {}

如今 Python 的 dict 子类中有意使用了这个技巧,因为否则代码会使用 mydict(self=123) 初始化 dict 子类会破坏初始值设定项。解决方法是:

 def __init__(*args, **kwargs):
self, *args = args
# On Python 2 without unpacking generalizations you'd use the more repetitive:
# self, args = args[0], args[1:]

它强制 self 被纯粹作为位置参数接受(由实例构建机制隐式传递)。有关现实世界用法的示例,请参阅 the implementation of collections.Counter .

关于python - 为什么 `*args` 的值很奇怪?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36440419/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com