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

Ghe*_*Ace 1 python function python-2.7 dictionary-missing

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

if collection[ key ]: # if exist
    #do this
else: # if no exist
    #do this
Run Code Online (Sandbox Code Playgroud)

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

collection = {}
def collection.__missing__():
    return false
Run Code Online (Sandbox Code Playgroud)

终端上面的代码给了我:

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

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

sbe*_*rry 6

这是你如何做到的:

if key in collection:
Run Code Online (Sandbox Code Playgroud)

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

if collection.get(key, None):
Run Code Online (Sandbox Code Playgroud)

如果你想使用__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"
Run Code Online (Sandbox Code Playgroud)

OUTPUT

one
Too bad, 2 does not exist
Run Code Online (Sandbox Code Playgroud)