【问题标题】:Catch if someone tries to set a class instance's variable directly [duplicate]如果有人尝试直接设置类实例变量,请捕获 [重复]
【发布时间】:2021-01-30 14:46:47
【问题描述】:

假设我有一个需要预处理输入变量x 的类。为此,我在这个类中实现了一个函数来设置变量(包括预处理)。为了使算法万无一失,我想知道是否有办法捕捉用户尝试手动设置x 的尝试,而不是调用正确的函数。作为一个小的虚拟示例,请考虑以下内容:

class dummy(): 
    def __init__(self, x):
        # This function initializes the instance
        self.x = x
    
    def adjust_x(self):
        # This function makes some change to x
        self.x += 5
        
    def set_x(self, x):
        # This function initializes x correctly
        self.x = x
        self.adjust_x()
        
instance = dummy(3)
print('Initialized correctly, the value of x is: ' + str(instance.x))

# We can also set x later on, using the correct function
instance.set_x(3)
print('Calling the function to set x, we get: ' + str(instance.x))

# However, if the user would try to set x directly, the variable does not get
# correctly adjusted:
instance.x = 3
print('Direct setting: ' + str(instance.x) + ' (/= 8, because instance.adjust_x() was not called)')

有没有办法抓住某人使用instance.x 设置x?在这种情况下,我想提出错误或警告。

【问题讨论】:

    标签: python python-3.x class instance


    【解决方案1】:

    在 Python 中,您可以通过在属性前面加上双下划线来限制属性的访问(相当于将字段的访问修饰符设置为私有)。

    示例

    class Object():
      def __init__(self, name):
        self.__name = name
    

    尝试访问instance.nameinstance.__name 会引发AttributeError

    注意

    正如@mkrieger1 指出的那样,双下划线并不是意味着 阻止访问,但我发现它确实有效。有关 Python 中私有变量的更多信息,请参阅here

    【讨论】:

    • 双下划线不是为了防止访问,而是为了防止在子类中意外覆盖父类的变量。
    • 我明白了。你能推荐一种更好的方法来阻止访问吗?
    • @J.Galt 据 所知,没有其他方法可以阻止访问。您可以在 Python 官方文档here 中阅读有关私有变量的更多信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-16
    • 1970-01-01
    • 2017-01-08
    • 1970-01-01
    相关资源
    最近更新 更多