从现有类对象中修改/删除\uu dunder \uuuuuu方法是否安全?

2024-04-26 14:17:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我想到了一个疯狂的延迟加载方法,在运行时应该从类型中移除一个datamodel钩子(影响所有实例)。这工作正常/如预期:

>>> class Crazy: 
...     def __getattr__(self, attr): 
...         del Crazy.__getattr__ 
...         return 'world' 
... 
>>> c = Crazy() 
>>> c.hello 
'world'
>>> c.hello 
AttributeError: 'Crazy' object has no attribute 'hello'

我记得在Python中不可能解析实例上的dunder名称monkeypatched,但是不确定动态修改类型的dunder名称是否有任何缺陷。你知道吗

这种行为在Python中有保证/可靠吗?你知道吗


Tags: 实例方法self名称类型helloworlddef