Skip to main content
 首页 » 编程设计

python之如何检查属性是否具有在 __init__ 中定义的默认值

2025年05月04日15lyhabc

如何检查对象的属性是否已被用户设置?目前,我有一个类

class foo: 
    def __init__(self): 
        self.bar = 'baz' 

稍后我想检查用户是否设置了 bar 的值,即用类似的东西

my_foo = foo() 
my_foo.bar = 'mybaz' 

所以我想知道上面的第二行是否被调用(如果没有则发出警告)。我有两个解决方案,但我都不喜欢其中任何一个:

  1. 检查 my_foo.bar 是否等于默认值。但可能是用户将 my_foo.bar 设置为相同的值,然后我不想发出警告。

  2. 不要在__init__中设置默认值,只有在使用时才设置。然后可以使用 getattr() 检查并使用 setattr() 进行设置。

我确信有一种我没有想到的优雅的 Pythonic 方式来做到这一点。

请您参考如下方法:

使用 @property 装饰器构造 getter 和 setter,当用户更改属性时让 setter 告诉您,示例如下

class Foo: 
 
    def __init__(self): 
        self._x_was_modified = False 
        self._x = None 
 
    @property 
    def x(self): 
        return self._x 
 
    @x.setter 
    def x(self, value): 
        self._x_was_modified = True 
        self._x = value 
 
foo = Foo() 
print('x was modified by user: {}'.format(foo._x_was_modified)) 
foo.x = 42 
print('x was modified by user: {}'.format(foo._x_was_modified)) 

这将输出:

x was modified by user: False 
x was modified by user: True