Python:可以使属性访问严格私有吗? [英] Python: Possible to make attribute access strictly private?

查看:60
本文介绍了Python:可以使属性访问严格私有吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个包含需要在各种实例方法之间重用的字典的类,但是我想使该字典只能从特定的实例方法中写入,那有可能吗?

If I have a class that contains a dictionary that I need to reuse among various instance methods, but I want to make that dictionary only writable from a specific instance method, is that possible?

在此代码中:

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是唯一可以以与阻止从类外部写入字典相同的方式写入字典的方法?

Is there a way to ensure that add_to_dict is the only method that can write to the dictionary in the same way that mangling prevents writing to it from outside the class?

我的用例在IronPython的托管版本中,因此inspect.currentframe不能如以下几个答案中所述.不过,这应该适用于非托管的IronPython或其他版本.

My use case is in a hosted version of IronPython, so inspect.currentframe doesn't work as mentioned in a couple answers below. Though, that should work for unhosted IronPython or other versions.

推荐答案

尽管我不知道您为什么要这样做,但我认为这可能对您有用:

Although I have no idea why you would want to do this, I think this could work for you :

第一种方法:

class my_class:
    def __init__(self):
        pass
    @property
    def some_variable(self):
        return self.__some_variable

    @some_variable.setter
    def some_variable(self, value):
        current_frame = inspect.currentframe()
        calling_function = inspect.getouterframes(current_frame, 2)[1][3]
        if (calling_function != "allowed_func_name"):
            raise Exception()
        self.__some_variable = value

第二种方法:

class my_class:
    def __init__(self):
        self.some_variable_set_flag = False
        pass
    def some_func(self, value):
        self.some_variable_set_flag = True
        try :
            self.some_variable = value
        finally :
            self.some_variable_set_flag = False

    @property
    def some_variable(self):
        return self.__some_variable

    @some_variable.setter
    def some_variable(self, value):
        if (not self.some_variable_set_flag):
            raise Exception()
        self.__some_variable = value

  • 这种方法不会为您提供全面的保护,但需要手动覆盖.
  • 它是一种抽象的方式(如果有其他人会寻找它的话).

    Its in an abstract way (if anyone else would look for this some time).

    这篇关于Python:可以使属性访问严格私有吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆