- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我遇到了 Borg design并认为它很适合我正在做的事情,但是我在使用它时收到了 DeprecationWarning
(我目前使用的是 Python 2.6,但很快就会转移到更新的版本)。
在评论中找到的新式版本是:
class Borg(object):
_state = {}
def __new__(cls, *p, **k):
self = object.__new__(cls, *p, **k)
self.__dict__ = cls._state
return self
但是,当创建带有参数的实例时会给出 DepricationWarning
:
DepricationWarning: object.__new__() takes no parameters
有没有一种方法可以在不使用带参数的 object.__new__()
的情况下使用 Borg 设计?
最佳答案
您不必将参数传递给 __new__
,它们会自动传递给 __init__
。 object.__new__
无论如何都不使用这些参数。这是the man himself对此事说:
There's no point in calling object.__new__() with more than a class parameter, and any code that did so was just dumping those args into a black hole.
所以只需这样做:
class Borg(object):
_state = {}
def __new__(cls, *p, **k):
self = object.__new__(cls)
self.__dict__ = cls._state
return self
def __init__(self, foo):
print(foo)
测试它:
>>> import borg
>>> b = borg.Borg(foo='bar')
bar
(仅使用 2.7 进行测试,假设它也适用于 2.6。)
关于python - 具有新型类的 Borg 设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8992241/
我正在使用相互包含模块的 Borg 模式。请参阅下面的示例代码(不是真实代码,但它显示了问题)。在这种情况下,我有两个不同的 Borgs,因为解释器认为类名(我猜是类)是不同的。 有没有办法在这种情况
我正在考虑在我的项目中使用单例模式,所以我搜索了 StackOverflow 以找到一种 pythonic 方式来实现它。我找到了 this question公认的答案是“具有函数(而不是类)的模块可
我遇到了 Borg design并认为它很适合我正在做的事情,但是我在使用它时收到了 DeprecationWarning(我目前使用的是 Python 2.6,但很快就会转移到更新的版本)。 在评论
我正在使用 borg 模式在对象之间共享状态: class Borg: __shared_state = {} def __init__(self): self.__d
我知道使用此模式是为了创建具有相同状态的多个实例,但我真的不明白它是如何工作的。 class Borg: _shared_state = {} def __init__(self):
我刚刚在网上偶然发现了这些有趣的代码: http://code.activestate.com/recipes/66531/ class Borg: __shared_state = {}
我看到了这个 Borg 单例模式代码,但我无法理解我添加到单例对象的新成员是如何附加到 __shared_state = {} 字典的。 这是单例代码 class Borg(object):
我在单例中使用 QTimer 实现了一个计时器。单例是使用 Borg 实现的图案。如果我在 Singleton 的函数内使用单次启动 QTimer,它将不会被执行。在单例之外的函数中进行相同的调用效果
我正在使用来自不同网站的 API,该 API 会返回我的用户用来购买虚拟商品的几个“价格点 URL”。 我应该将这些结果缓存至少一个小时,因为它们不会对系统上的价格点进行太多更改。 (而且我们想节省我
为什么 Borg pattern优于Singleton pattern ? 我问是因为我看不出它们有什么不同。 博格: class Borg: __shared_state = {} # in
据我所知,Google 的 Kubernetes 是基于 Google 的 Borg;然而,Borg 似乎比 Kubernetes 更大。我的理解是,Borg 是一个大系统,包含像 Kubernete
我是一名优秀的程序员,十分优秀!