1. 程式人生 > >Python 一些特別函式 __getitem__ __getattr__

Python 一些特別函式 __getitem__ __getattr__

Python 內建的一些函式,通過過載它們,可以定製自己想要的功能。特別說明一下包含 item 類的函式是通過下標[]操作字典的,包含 attr 類函式是通過 . 操作屬性的。

class A(object):
    def __init__(self, *args, **kwargs):
        print 'call func init'
        self.item = {'0':'a', '1':'b', '2':'c'}
        super(A, self).__init__(*args, **kwargs)
    def __repr__(self, *args, **kwargs):
        print 'call func repr'
        return object.__repr__(self, *args, **kwargs)
    def __new__(self, *args, **kwargs):
        print 'call func new'
        return object.__new__(self, *args, **kwargs)
    def __str__(self, *args, **kwargs):
        print 'call func str'
        return object.__str__(self, *args, **kwargs)
    def __delattr__(self, *args, **kwargs):
        print 'call func del attr'
        return object.__delattr__(self, *args, **kwargs)
    def __setattr__(self, *args, **kwargs):
        print 'call func set attr'
        return object.__setattr__(self, *args, **kwargs)
    def __getattribute__(self, *args, **kwargs):
        print 'call func get attr'
        return object.__getattribute__(self, *args, **kwargs)
    def __getitem__(self, key):
        print 'get item[\'%s\']' % key  
        return self.item.get(key)
    def __setitem__(self, key, value):
        print 'set item[\'%s\'] = \'%s\'' % (key, value) 
        self.item.update({key:value})
    def __delitem__(self, key):  
        del self.item[key]
        print 'delete item[\'%s\']' % key  

a = A()
repr(a)
str(a)
a.name = 'hanson'
print a.name
del a.name
print a['0']
a['3'] = 'd'
print a.item
del a['1']
print a.item

輸出結果:
call func new
call func init
call func set attr
call func repr
call func str
call func repr
call func set attr
call func get attr
hanson
call func del attr
get item['0']
call func get attr
a
set item['3'] = 'd'
call func get attr
call func get attr
{'1': 'b', '0': 'a', '3': 'd', '2': 'c'}
call func get attr
delete item['1']
call func get attr
{'0': 'a', '3': 'd', '2': 'c'}

對於getattr,還有另外一點,就是首先回去self.__dicts__裡搜尋,如果沒有找到,才會來呼叫getattr。例如以下例子:

class A(object):
    def __init__(self):
        self.name = 'from __dicts__: zdy'

    def __getattr__(self, item):
        if item == 'name':
            return 'from __getattr__: zdy'
        elif item == 'age':
            return 26

a = A()
print a.name # 從__dict__裡獲得的
print a.age # 從__getattr__獲得的

輸出結果:
from __dicts__: zdy
26

從該例子可以看出,在self.__dicts__和self.__getattr__都有定義name情況下,預設返回了self.__dicts__的,如果沒有搜到,才是返回__getattr__定義的。