Python 数据模型

一、Python解释器碰到特殊句法时,会使用特殊方法去激活一些基本的对象操作,这些特殊方法的名字以两个下划线开头,以两个下划线结尾

  - 举例:obj[key]背后就是__getitem__方法

  - 没有实现__getitem__方法,无法使用[]获取类中的dict

1 class A:
2     adict = dict(one=1,two=2)
3 
4 a = A()
5 print(a['one'])
6 print(a['two'])

TypeError: 'A' object is not subscriptable

  - 实现__getitem__方法后,可以使用[]

class A:
    adict = dict(one=1,two=2)
    def __getitem__(self, item):
        return A.adict[item]
a = A()
print(a['one'])
print(a['two'])

1
2

猜你喜欢

转载自www.cnblogs.com/StackNeverOverFlow/p/9775525.html