[英]Python: How can I defeat a lock in mangled variable which uses a special method?
In python, one is able to use special methods to achieve something similar to operator overloading in C++ by defining a special method for __setattr__. 在python中,可以通过为__setattr__定义一种特殊的方法来使用特殊的方法来实现类似于C ++中的运算符重载的功能。 I have seen some coders use this to create a read-only lock using a mangled variable name.
我已经看到一些编码器使用此变量使用变形变量名来创建只读锁。 That's pretty clever until I need to an element to an array of the locked class.
在需要将元素添加到锁定类的数组之前,这是非常聪明的。 For example, FreeIPA implements this .
例如, FreeIPA实现了this 。 This would be fairly straightforward to defeat by simply setting exampleArray._ReadOnly__locked = False, except this is ALSO caught by the __setattr__ special method and results in the error
只需设置exampleArray._ReadOnly__locked = False,就可以很轻松地解决这个问题,除非这也是__setattr__特殊方法捕获的,并导致错误
"ipa: ERROR: AttributeError: locked: cannot set NameSpace._ReadOnly__locked to False"
“ ipa:错误:AttributeError:已锁定:无法将NameSpace._ReadOnly__locked设置为False”
Is there a simple and clever way to set this back to read-write mode so that I can insert my value into the array? 是否有一种简单聪明的方法将此设置回读写模式,以便可以将值插入数组?
As noted in the docstring, you can use the default implementation of __setattr__
from object
. 如文档字符串中所述,您可以使用
object
的__setattr__
的默认实现。
class ReadOnly(object):
def __setattr__(self, name, value):
raise AttributeError("This instance is read only.")
r = ReadOnly()
object.__setattr__(r, 'name', 'value')
print r.name # 'value'
The potential issue here is when your parent class does something special when setting objects. 这里的潜在问题是当您的父类在设置对象时做一些特殊的事情。 In this case, your resulting instance may be inconsistent.
在这种情况下,您生成的实例可能会不一致。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.