Chen Jian

导航

 

特殊函数一般以__methodname__的形式命名,如:__init__(构造方法), __getitem__、 __setitem__(subscriptable所需method), __delitem__(del obj[key]所需method), __len__(len(…)所需method)等;

以下以什么都不做的Something类,结合lambda表达式,来说明这些特殊函数;

>>> class Something:

... pass

...

>>> s = Something()

>>> s['key1']

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: 'Something' object is not subscriptable

subscriptable相关的函数是 __getitem__、 __setitem__,顾名思义,两者分别用于获取和设置相应的key的值;

Something.__getitem__ = lambda self, key: key

__getitem__简单的返回key;

>>> s['key1']

'key1'

>>> s[1]

1

>>> s[(1,2,3)]

(1, 2, 3)

注意:不可变类,都可以作为key;

>>> s[1] = 2

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: 'Something' object does not support item assignment

增加__setitem__方法,简单的打印key-value对;

>>> Something.__setitem__ = lambda self, key, value: print(repr(key) + ":" + repr(value))

>>> s[1] = 33

1:33

>>> s[(1,2,3)] = "333"

(1, 2, 3):'333'

>>> del s[1]

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

AttributeError: __delitem__

增加__delitem__方法,简单打印

>>> Something.__delitem__ = lambda self, key : print(repr(key) + " is deleted")

>>> del s[23]

23 is deleted

>>> len(s)

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: object of type 'Something' has no len()

增加__len__方法,简单返回1

>>> Something.__len__ = lambda self : 1

>>> len(s)

1

posted on 2016-08-05 10:02  Chen Jian  阅读(895)  评论(0编辑  收藏  举报