>>> class Const(object): # an overriding descriptor, see later
... def __init__(self, value):
... self.value = value
... def __set__(self, value):
... self.value = value
... def __get__(self, *_): # always return the constant value
... return self.value
...
>>>
>>> class X(object):
... c = Const(23)
...
>>> x=X()
>>> print(x.c) # prints: 23
23
>>> x.c = 42
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __set__() takes 2 positional arguments but 3 were given
有什么作用
需要 2 个位置参数,但给出了 3 个`TypeError: __set__()
是什么意思?
__set__()
是属于描述符类型Const
的方法吗?
__set__()
的签名是什么?
谢谢。
_set_ 的签名记录在here:
object._set_(self, instance, value) 调用以设置属性 将所有者类的实例实例设置为新值 value。
TypeError是告诉你缺少instance参数,应该是
def __set__(self, instance, value): ...
。
这是使 Constant 类正常工作的一种方法:
class Const(object):
def __init__(self, value):
object.__setattr__(self, '_value', value)
def __set__(self, inst, value):
raise TypeError('Cannot assign to a constant')
def __get__(self, inst, cls=None):
return self._value
class X(object):
c = Const(23)
在交互式会话中尝试一下可以得到:
>>> x = X()
>>> print(x.c)
23
>>> x.c = 42
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
x.c = 42
File "/Users/raymond/Documents/try_forth/tmp.py", line 5, in __set__
raise TypeError('Cannot assign to a constant')
TypeError: Cannot assign to a constant