【发布时间】:2016-05-21 21:33:05
【问题描述】:
我已经阅读了各种“Python 实例中没有真正的私有数据”的帖子,但我们都知道在 Perl 和 JavaScript 中使用闭包来有效地实现私有数据。那么为什么不用 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']
您可以对实例事物做什么来获得对原始字符串的读取访问权限(忽略我的弱加密)或对其进行写入访问?
这周我正在教我的学生有关 Python 的课程,我试图理解为什么在给定闭包的情况下,JavaScript 和 Perl 的技术不适用于 Python。
【问题讨论】:
标签: javascript python perl closures private