小编jos*_*lle的帖子

`dict.pop` 忽略 `collections.defaultdict(default_factory)` 设置的默认值

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

python dictionary python-3.x defaultdict python-collections

1
推荐指数
1
解决办法
213
查看次数

对列表进行子类化时,super() 是什么?如何直接访问底层列表?

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 list subclass super superclass

0
推荐指数
1
解决办法
92
查看次数