c#自定义Attribute获取接口实现示例代码
262
2022-08-27
Python从门到精通(二):包装-06-对象高级功能(面向对象python详细教程)
一、自定义容器
mport collectionsimport bisectclass 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 weakrefclass 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_mappingclass LoggedDict(dict): passd = LoggedDict()d['x'] = 23print(f"d['x'] = {d['x']}")
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~