Python中的__getitem__和__setitem__特殊方法

在Nova的源码中,基本上所有的类都继承NovaObject,这些类可以直接以a[key]=value的方式给对象增加新的属性并且通过a[key]的方式获取对象属性,这是因为在NovaObject中实现了两个方法getitemsetitem
下面是NovaObject的部分源码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class NovaObject(object):
...
def __getitem__(self, name):
"""For backwards-compatibility with dict-based objects.
NOTE(danms): May be removed in the future.
"""
return getattr(self, name)
def __setitem__(self, name, value):
"""For backwards-compatibility with dict-based objects.
NOTE(danms): May be removed in the future.
"""
setattr(self, name, value)
Jerky Lu wechat
欢迎加入微信公众号