简体   繁体   English

自定义删除器方法示例

[英]Example of a custom deleter method

I have come across various examples of a custom getter or setter , but what would be a use case of when a custom deleter would be used?我遇到了自定义gettersetter的各种示例,但是使用自定义deleter的用例是什么? So far an example that I have is just something like this:到目前为止,我的一个例子是这样的:

def __delattr__(self, attr):
    print('Deleting attr %s' % attr)
    super().__delattr__(attr)

It's a standard datamodel hook for customizing what a statement del obj.attr will do, instead of (or in addition to) removing the attribute from the instance __dict__ .这是一个标准的数据模型钩子,用于自定义语句del obj.attr将执行的操作,而不是(或除此之外)从实例__dict__中删除属性。 So, user code is free to implement whatever they want!因此,用户代码可以自由实现他们想要的任何东西!

As an example, you could use it as a "soft delete" feature, eg to hide an attribute from public access without actually removing the data behind it.例如,您可以将其用作“软删除”功能,例如隐藏属性以防止公共访问,而无需实际删除其背后的数据。 Personally, I have used it to invalidate caches when the corresponding get attribute method has a caching layer in front of it.就个人而言,当相应的 get 属性方法前面有缓存层时,我使用它来使缓存无效。

For a stdlib example, consider the Mock class.对于 stdlib 示例,请考虑Mock class。 By default, mock instances will generate child mocks for any attribute access.默认情况下,模拟实例将为任何属性访问生成子模拟。 The public API to "opt-out" of a child mock being auto-generated on a particular name is implemented via a custom __delattr__ .公共 API “选择退出”在特定名称上自动生成的子模拟是通过自定义__delattr__实现的

>>> from unittest.mock import Mock  
>>> mock = Mock()   
>>> del mock.attr2  # prevent mock.attr2 from working
>>> mock.attr1  
<Mock name='mock.attr1' id='4414043216'>
>>> mock.attr2
AttributeError: attr2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM