【发布时间】: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