Python 会dict.pop(key[, default])忽略由 设置的默认值,collections.defaultdict(default_factory)如以下代码片段所示:
from collections import defaultdict
d = defaultdict(lambda: 1)
d['a']
d['b'] = 2
print(d.pop('a')) # 1
print(d.pop('b')) # 2
print(d.pop('c', 3)) # 3
d.pop('e') # KeyError: 'e'
Run Code Online (Sandbox Code Playgroud)
d是一个defaultdict(lambda: 1). d.pop('e')导致KeyError. 这是故意的吗?不应该d.pop('e')返回,1因为这是设置的默认值defaultdict?
class Foo(list):
def bar(self):
return super().__getitem__(slice(None))
def baz(self):
return super()
a = Foo([0, 1, 2, 3])
print(a.bar()) # [0, 1, 2, 3]
print(a.baz()) # <super: <class 'Foo'>, <Foo object>>
# a.bar() provides a copy of the underlying list as can be seen from the fact that each result of a.bar() has a different id
print(id(a.bar())) # id1
print(id(a.bar())) # id2 != id1
Run Code Online (Sandbox Code Playgroud)
我最近有一个用例,我需要子类化list并需要从子类 ( ) 内访问底层列表Foo。我以为super()会提供基础列表,但没有。相反,我必须super().__getitem__(slice(None))提供底层列表的副本。如何直接访问底层列表?我的理解中缺少什么super()?
非常感谢!
python ×2
defaultdict ×1
dictionary ×1
list ×1
python-3.x ×1
subclass ×1
super ×1
superclass ×1