【发布时间】:2018-04-24 21:28:40
【问题描述】:
如果我有一个包含字典的类,我需要在各种实例方法中重用该字典,但我想让该字典只能从特定实例方法写入,这可能吗?
在这段代码中:
class GoodClass:
def __init__(self):
# name mangling enabled!
self.__dict = {}
def __repr__(self):
return str(self.__dict)
def add_to_dict(self, key, item):
# this should be the only method that can write to self.__dict
try:
self.__dict[key] += [item]
except KeyError:
self.__dict[key] = [item]
def make_items(self, n_items=3, important_param=1):
# do the important stuff
for i in range(n_items):
item = "param: {}".format(important_param)
self.add_to_dict("important_items", item)
def this_is_bad(self):
# don't want this to be possible
self.__dict["this is bad"] = ["quite bad"]
c = GoodClass()
c.make_items()
c.this_is_bad()
# c.__dict["can't do this"] = ["thanks mangling!"]
print(c)
# {'important_items': ['param: 1', 'param: 1', 'param: 1'], 'this is bad': ['quite bad']}
有没有办法确保add_to_dict 是唯一可以写入字典的方法,就像修改防止从类外部写入字典一样?
我的用例在 IronPython 的托管版本中,因此inspect.currentframe 不能像下面几个答案中提到的那样工作。不过,这应该适用于非托管 IronPython 或其他版本。
【问题讨论】:
-
...为什么?即使在带有
private说明符的语言中,我也想不出有这样的功能。 -
特别是,如果您希望其他方法能够读取
self.__dict,并且您希望__init__能够初始化 @ 987654327@,但您只希望一种特定的方法能够将项目添加到self.__dict,这不是 Python 的对象模型的工作方式。 -
假设您可以使用
__setattr__魔术方法来做到这一点,但@user2357112 是正确的,我的回答是......为什么? -
公开阅读不是问题,可以有一个
GoodClass.dict属性。这个想法是防止另一种方法直接覆盖self.__dict["important_items"] -
您可以将
self.__dict重命名为self._only_write_from_add_to_dict_method(既易于实现,又对类用户而言显而易见)。
标签: python ironpython