Python Class: overwrite `self`(Python类:覆盖`self`)
本文介绍了Python类:覆盖`self`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的python脚本中,我有一个存储Processo
对象的全局存储(一个简单的全局dict
)。它是在我的程序执行过程中填满的。由于性能原因,它的存在是为了避免创建重复的Processo
对象。
因此,对于class Processo
,我希望在创建期间验证它是否已在全局存储上。
self
。为此,我使用getfromStorage()
。
class Processo:
def __init__(self, name, ...): # ... for simplicity
self.processoname = name
self = getfromStorage(self)
不知道它是否有用,但是.
def getfromStorage(processo):
if processo.processoname in process_storage:
return process_storage[processo.processoname]
return processo
我如何实现这一点?是我遗漏了什么,还是我的设计有误?
推荐答案
无法使用__init__
合理地完成此模式,因为__init__
仅初始化已存在的对象,并且您无法更改调用方将获得的内容(您可以重新绑定self
,但这只会将您与正在创建的对象切断,调用方有自己的单独别名,不受影响)。
正确的做法是覆盖实际的构造函数__new__
,它允许您返回您可能创建也可能不创建的新实例:
class Processo:
def __new__(cls, name, ...): # ... for simplicity
try:
# Try to return existing instance from storage
return getfromStorage(name)
except KeyError:
pass
# No instance existed, so create new object
self = super().__new__(cls) # Calls parent __new__ to make empty object
# Assign attributes as normal
self.processoname = name
# Optionally insert into storage here, e.g. with:
self = process_storage.setdefault(name, self)
# which will (at least for name of built-in type) atomically get either then newly
# constructed self, or an instance that was inserted by another thread
# between your original test and now
# If you're not on CPython, or name is a user-defined type where __hash__
# is implemented in Python and could allow the GIL to swap, then use a lock
# around this line, e.g. with process_storage_lock: to guarantee no races
# Return newly constructed object
return self
为了减少开销,我略微重写了getfromStorage
,所以它只接受名称并执行查找,如果失败则允许泡沫异常:
def getfromStorage(processoname):
return process_storage[processoname]
这意味着,当可以使用缓存的实例时,不需要重新构造不必要的self
对象。
__init__
;对象的构造是通过调用类的__new__
,然后对结果隐式调用__init__
来完成的。对于缓存的实例,您不希望重新初始化它们,因此需要一个空的__init__
(这样缓存的实例就不会因为从缓存中检索而被修改)。将所有的__init__
类行为都放在__new__
内部构造和返回新对象的代码中,并且只对新对象执行,以避免此问题。
这篇关于Python类:覆盖`self`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:Python类:覆盖`self`


基础教程推荐
猜你喜欢
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 求两个直方图的卷积 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 包装空间模型 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01