Skip to main content
 首页 » 编程设计

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

2025年05月04日20qq号

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

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