python getitem_Python 一些特别函数 __getitem__ __getattr__ | 学步园

本文介绍了Python中如何通过重载内置函数来自定义类的方法,包括初始化、字符串表示、属性获取等,并通过实例展示了getitem、setitem等方法的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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__定义的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值