您的位置:首页 > 编程语言 > Python开发

Python 一些特别函数 __getitem__ __getattr__

2011-12-20 19:10 459 查看
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__定义的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: