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`
				
        
 
            
        
             猜你喜欢
        
	     - 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
 - 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
 - python-m http.server 443--使用SSL? 2022-01-01
 - 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
 - 沿轴计算直方图 2022-01-01
 - 如何将一个类的函数分成多个文件? 2022-01-01
 - python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
 - pytorch 中的自适应池是如何工作的? 2022-07-12
 - 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
 - padding='same' 转换为 PyTorch padding=# 2022-01-01
 
				
				
				
				