为 Python 创建“常量”描述符类时出现问题[重复]

问题描述 投票:0回答:1
>>> 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__()
需要 2 个位置参数,但给出了 3 个`

是什么意思?

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

__set__()
的签名是什么?

谢谢。

python python-3.x exception constants descriptor
1个回答
2
投票

__

签名

_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
© www.soinside.com 2019 - 2024. All rights reserved.