gpt4 book ai didi

Python:如何将函数分配给对象属性?

转载 作者:太空宇宙 更新时间:2023-11-04 08:17:20 25 4
gpt4 key购买 nike

基本上这始于我在尝试查找字典中是否存在索引时遇到的问题:

if collection[ key ]: # if exist
#do this
else: # if no exist
#do this

但是当索引真的不存在时,它会抛出一个 KeyError。所以,阅读 Python 文档。如果定义了 missing(),它不会抛出 KeyError

collection = {}
def collection.__missing__():
return false

终端上的上述代码给我:

ghelo@ghelo-Ubuntu:~/Music$ python __arrange__.py
File "__arrange__.py", line 16
def allArts.__missing__():
^
SyntaxError: invalid syntax

那么,如何正确地做到这一点呢?顺便说一句,我需要在这上面使用 Python 2.7。在 Python 3 上运行时有区别吗?

最佳答案

这是你的做法:

if key in collection:

或者,正如@sdolan 所建议的,您可以使用 .get 方法,如果不存在则返回默认值(可选的第二个参数)。

if collection.get(key, None):

如果你想使用 __missing__ 你可以将它应用到一个扩展 dict 的类(在本例中):

class collection(dict):

def __missing__(self, key):
print "Too bad, {key} does not exist".format(key=key)
return None


d = collection()
d[1] = 'one'

print d[1]

if d[2]:
print "Found it"

输出

one
Too bad, 2 does not exist

关于Python:如何将函数分配给对象属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12016390/

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