Skip to main content
 首页 » 编程设计

Python 描述符 __get__ 和 __set__

2024年11月01日9tintown

我确定这将被标记为重复,但我真的不明白我在看什么。我已经查看了有关描述符的 Python 文档,但我已经用 Python 进行了两周的“编程”,但我真的不知道我在寻找什么!

这是我得到的:

>>> class Blub(object): 
...     def __init__(self, value): 
...             print('Blub is ' + value) 
...             self.value = value 
...     def __get__(self): 
...             print('Blub gets ' + self.value) 
...             return self.value 
...     def __set__(self, value): 
...             print('Blub becomes ' + value) 
...             self.value = value 
... 
>>> class Quish(object): 
...     def __init__(self, value): 
...             self.blub = Blub(value) 
...     def __get__(self): 
...             return self.blub 
...     def __set__(self, value): 
...             self.blub = Blub(value) 
...  

以下是我想发生但不知道该怎么做的情况:

>>> a = Quish('One') 
Blub is One 
>>> a.blub 
Blub gets One 
'One' 
a.blub = 'Two' 
Blub becomes Two 

为了实现这一点,我在 Blub 或 Quish 中做了什么。我这里有非常简单的类(class),但我有一个更复杂的版本,它可以完美运行,但前提是我输入:

>>> a.blub.__get__() 

我认为这些描述符的目的是让实际编写get() 和set() 变得不必要。我如何让它表现得像我想要的那样,或者 Python 不能那样做?

请您参考如下方法:

通常你不会直接使用描述符,而是使用 property ,这是一种易于使用的描述符实现。以下是您将如何使用它:

class Quish(object): 
    def __init__(self, value): 
        self.blub = value 
 
    @property 
    def blub(self): 
        print('Blub gets ' + self._blub) 
        return self._blub 
 
    @blub.setter 
    def blub(self, value): 
        print('Blub becomes ' + value) 
        self._blub = value 

如果你真的想写你自己的描述符,你的问题是它需要直接在类型上设置,而不是作为另一个实例属性,你需要处理一个描述符多个实例:

class Blub(object): 
    def __get__(self, instance, owner): 
        print('Blub gets ' + instance._blub) 
        return instance._blub 
 
    def __set__(self, instance, value): 
        print('Blub becomes ' + value) 
        instance._blub = value 
 
 
class Quish(object): 
    blub = Blub() 
 
    def __init__(self, value): 
        self.blub = value