我确信这将被标记为重复,但我真的不明白我在看什么。我已经检查了 Descriptors 上的 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 中该怎么做。我在这里有非常简单的课程,但我有一个更复杂的版本,它可以完美运行,但前提是我输入:
>>> a.blub.__get__()
我认为这些描述符的目的是使实际编写get () 和set () 变得不必要。我如何让它表现得像我想要的那样,或者 Python 不能这样做?