python什么是空类型_在Python中创建真正的空类型

如何创建自己的自定义容器?

class Empty(object):

def __init__(self, **kwargs):

object.__setattr__(self, '_obj', kwargs)

def __getattribute__(self, name):

obj = object.__getattribute__(self, '_obj')

try:

return obj[name]

except KeyError:

cls_name = object.__getattribute__(self, '__class__').__name__

raise AttributeError(

"'%(cls_name)s' object has no attribute '%(name)s'" % locals())

def __setattr__(self, name, val):

obj = object.__getattribute__(self, '_obj')

obj[name] = val

def __getitem__(self, key):

return getattr(self, key)

def __setitem__(self, key, val):

return setattr(self, key, val)

用法:

e = Empty(initial='optional-value')

e.initial

# 'optional-value'

e.val = 'foo'

e.val

# 'foo'

e.bad

# AttributeError: 'Empty' object has no attribute 'bad'

setattr(e, 'user', 'jdi')

e.user

# 'jdi'

e['user']

# 'jdi'

# note that you dont even see anything when you dir()

dir(e)

# []

# and trying to access _obj is protected

e._obj

#AttributeError: 'Empty' object has no attribute '_obj'

# But you could even set your own _obj attribute

e._obj = 1

e._obj

# 1

它会将所有内容存储在_obj字典下,因此您基本上可以获得一个与实际实例属性不冲突的干净空间.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值