为python创建”常量”描述符类时出现问题

Problems creating a “constant” descriptor class for Python

本问题已经有最佳答案,请猛点这里访问。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
>>> 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

什么?

TypeError: __set__() takes 2 positional arguments but 3 were given`

意味着什么?

__set__()是属于描述符类型Const的方法吗?

__set__()的签名是什么?

谢谢。


_uuu集合的签名__

_uuu set_uuu的签名记录在这里:

object.__set__(self, instance, value) Called to set the attribute on
an instance instance of the owner class to a new value, value.

类型错误的含义

typeerror告诉您实例参数丢失了,它应该是def __set__(self, instance, value): ...

制定解决方案

下面是使常量类正确工作的一种方法:

1
2
3
4
5
6
7
8
9
10
class Const(object):
    def __init__(self, value):
        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)

在交互式会话中进行尝试可以提供:

1
2
3
4
5
6
7
8
9
10
>>> 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