Python-Bunch模式

本文介绍了Bunch设计模式,一种让对象属性可通过构造器动态设置的模式。通过继承dict类,Bunch模式允许以命令行参数形式创建对象并设置属性,同时支持键值/属性值的遍历及查询。

“Bunch”设计模式:

首先,它能让我们以命令行参数的形式创建相关对象,并设置任何属性。

>>> class Bunch(dict):
	def __init__(self,*args,**kwds):
		super(Bunch,self).__init__(*args,**kwds)
		self.__dict__=self

		
>>> x=Bunch(age="54",address="Beijing")
>>> x.age
'54'

由于它继承自dict类,我们可以自然而然获得大量相关内容,如对于相关键值/属性值的遍历,或者简单查询一个属性是否存在。

>>> T=Bunch
>>> t=T(left=T(left='a',right='b'),right=T(left='c'))
>>> t.left
{'left': 'a', 'right': 'b'}
>>> t.left.right
'b'
>>> t['left']['right']
'b'
>>> "left" in t.right
True
>>> "right"in t.right
False


当您希望有一个灵活的对象,其属性可以从构造器中被动态设置时,也可以同样可以该模式实现。


摘自《Python算法教程》P34

### 关于享元模式的介绍 享元模式是一种结构型设计模式,它通过减少内存中对象的数量来节省存储空间。这种模式特别适用于当程序中有大量相似的对象时,可以通过共享这些对象的部分状态来降低资源消耗。 以下是实现享元模式的一个典型代码示例: ```python import random from typing import Dict class Flyweight: def __init__(self, shared_state: str): self._shared_state = shared_state def operation(self, unique_state: str): s = f"Shared State: {self._shared_state}" u = f"Unique State: {unique_state}" print(f"Flyweight displays {s} and {u}") class FlyweightFactory: _flyweights: Dict[str, Flyweight] = {} def __init__(self, initial_flyweights: list): for state in initial_flyweights: self._flyweights[state] = Flyweight(state) def get_flyweight(self, key: str) -> Flyweight: if not self._flyweights.get(key): print(f"Not cached flyweight created with key `{key}`") self._flyweights[key] = Flyweight(key) return self._flyweights[key] def add_car_to_police_database( factory: FlyweightFactory, plates: str, owner: str, brand: str, model: str, color: str ): print("\nClient: Adding a car to database.") flyweight = factory.get_flyweight(plates) flyweight.operation(f"{owner}, {brand}, {model}, {color}") if __name__ == "__main__": """ The client code usually creates a bunch of pre-populated flyweights in the initialization stage of the application. """ factory = FlyweightFactory(["A1", "B2", "C3"]) add_car_to_police_database(factory, "A1", "John Doe", "Tesla", "Model S", "Black") # Existing flyweight used add_car_to_police_database(factory, "D4", "Jane Smith", "BMW", "M5", "Red") # New flyweight created ``` 上述代码展示了如何创建并使用享元对象[^1]。`FlyweightFactory` 类负责管理多个 `Flyweight` 对象实例,并根据需要返回已存在的或者新创建的实例。这有助于减少重复数据的冗余存储需求。 ### § 1. 如何判断某个场景适合应用享元模式? 2. 在实际开发过程中,享元模式可能会遇到哪些性能瓶颈? 3. 如果不采用享元模式优化对象存储,会有哪些潜在的风险或后果? 4. 除了 Python 外,在其他编程语言中实现享元模式有哪些需要注意的地方? 5. 当前主流框架是否有内置支持享元模式的功能模块?
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值