gpt4 book ai didi

javascript - 重访 Python 私有(private)实例数据

转载 作者:数据小太阳 更新时间:2023-10-29 06:05:41 28 4
gpt4 key购买 nike

我读过各种“Python 实例中没有真正私有(private)数据”的帖子,但我们都知道在 Perl 和 JavaScript 中使用闭包来有效实现私有(private)数据。那么为什么不用 Python 呢?

例如:

import codecs

class Secret:
def __private():
secret_data = None

def __init__(self, string):
nonlocal secret_data
if secret_data is None:
secret_data = string

def getSecret(self):
return codecs.encode(secret_data, 'rot_13')

return __init__, getSecret

__init__, getSecret = __private()

现在我们做:

>>> thing = Secret("gibberish")
>>> thing.getSecret()
'tvoorevfu'
>>> dir(thing)
['_Secret__private', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'getSecret']

您可以对实例 thing 做些什么来获得对原始字符串的读取权限(忽略我的弱加密)或对其的写入权限?

这周我正在给我的学生讲授 Python 类(class),我试图理解为什么在给定闭包的情况下,JavaScript 和 Perl 的技术不适用于 Python。

最佳答案

如果您只想访问 原始文件,这并不难,因为 Python 函数实现了相当彻底的检查 api。您可以通过以下方式访问原始 secret :

thing = Secret("gibberish")
# __init__ doesn't need to be used here; anything defined within the closure will do
thing.__init__.__func__.__closure__[0].cell_contents

而且,嘿!我们得到了原始值。

修改该值比较困难(但并非不可能)(参见 here )。为此设置修改:

import ctypes
...

thing = Secret("gibberish")
cell = ctypes.py_object(thing.__init__.__func__.__closure__[0])
new_value = ctypes.py_object('whatever')
ctypes.pythonapi.PyCell_Set(cell, new_value)

thing.getSecret()

关于javascript - 重访 Python 私有(private)实例数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35333721/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com