当前位置 : 主页 > 编程语言 > python >

Python从门到精通(二):包装-06-对象高级功能

来源:互联网 收集:自由互联 发布时间:2022-06-24
一、自定义容器 mport collections import bisect class SortedItems ( collections . Sequence ): def __init__ ( self , initial = None ): self . _items = sorted ( initial ) if initial is not None else [] # Required sequence methods def __

一、自定义容器

mport collections
import bisect

class SortedItems(collections.Sequence):
def __init__(self, initial=None):
self._items = sorted(initial) if initial is not None else []

# Required sequence methods
def __getitem__(self, index):
return self._items[index]

def __len__(self):
return len(self._items)

# Method for adding an item in the right location
def add(self, item):
bisect.insort(self._items, item)

item_list = SortedItems([5, 1, 3])
print(f'item list = {list(item_list)}')
print(f'item_list[0] = {item_list[0]}, item_list[-1] = {item_list[-1]}')
item_list.add(2)
print(f'item_list = {list(item_list)}')class Items(collections.MutableSequence):
def __init__(self, initial=None):
self._items = list(initial) if initial is not None else []

# Required sequence methods
def __getitem__(self, index):
return self._items[index]

def __setitem__(self, index, value):
self._items[index] = value

def __delitem__(self, index):
del self._items[index]

def insert(self, index, value):
self._items.insert(index, value)

def __len__(self):
return len(self._items)


a_item = Items([1, 2, 3])
print(f'len of a is: {len(a_item)}')

a_item.append(4)
a_item.append(2)
a_item.count(2)
a_item.remove(2)

二、创建单例

import weakref

class CachedSpamManager2:
def __init__(self):
self._cache = weakref.WeakValueDictionary()

def get_spam(self, name):
if name not in self._cache:
temp = Spam3._new(name) # Modified creation
self._cache[name] = temp
else:
temp = self._cache[name]
return temp

def clear(self):
self._cache.clear()

class Spam3:
def __init__(self, *args, **kwargs):
raise RuntimeError("Can't instantiate directly")

# Alternate constructor
@classmethod
def _new(cls, name):
self = cls.__new__(cls)
self.name = name
return self

三、Mixin功能

def logged_mapping(cls):
"""第二种方式:使用类装饰器"""
cls_getitem = cls.__getitem__
cls_setitem = cls.__setitem__
cls_delitem = cls.__delitem__

def __getitem__(self, key):
print(f'Getting {str(key)}')
return cls_getitem(self, key)

def __setitem__(self, key, value):
print(f'Setting {key} = {value!r}')
return cls_setitem(self, key, value)

def __delitem__(self, key):
print(f'Deleting {str(key)}')
return cls_delitem(self, key)

cls.__getitem__ = __getitem__
cls.__setitem__ = __setitem__
cls.__delitem__ = __delitem__
return cls


@logged_mapping
class LoggedDict(dict):
pass

d = LoggedDict()
d['x'] = 23
print(f"d['x'] = {d['x']}")
上一篇:【推荐】5个常用的Python标准库!
下一篇:没有了
网友评论