python - 为什么在 __init__ 函数中声明描述符类会破坏描述符功能?

标签 python descriptor

在下面的 B 类中,我希望在为 B().a 赋值时调用 A 类中的 __set__ 函数。相反,将值设置为 B().a 会用该值覆盖 B().a。分配给 C().a 的 C 类工作正常,但我想为每个用户类都有一个单独的 A 实例,即我不想在 C 的一个实例中更改“a”( ) 在所有其他情况下更改 'a'。我写了几个测试来帮助说明问题。你能帮我定义一个能同时通过 test1 和 test2 的类吗?

class A(object):
    def __set__(self, instance, value):
        print "__set__ called: ", value

class B(object):
    def __init__(self):
        self.a = A()

class C(object):
    a = A()

def test1( class_in ):
    o = class_in()
    o.a = "test"
    if isinstance(o.a, A):
        print "pass"
    else:
        print "fail"

def test2( class_in ):
    o1, o2 = class_in(), class_in()
    if o1.a is o2.a:
        print "fail"
    else:
        print "pass"

最佳答案

根据documentation :

The following methods only apply when an instance of the class containing the method (a so-called descriptor class) appears in the class dictionary of another new-style class, known as the owner class. In the examples below, “the attribute” refers to the attribute whose name is the key of the property in the owner class’ __dict__. Descriptors can only be implemented as new-style classes themselves.

所以你不能在实例上有描述符。

但是,由于描述符获取用于访问它的实例的引用,只需将其用作存储状态的键,您可以根据实例有不同的行为。

关于python - 为什么在 __init__ 函数中声明描述符类会破坏描述符功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1004168/

相关文章:

python - 在 python 中获取命令行参数时出错

python - 使用 protobuf,如何从已解析的对象中删除字段?

Python:正确分配测试描述符

Python - 类上的描述符用于*设置*属性

python - Python 中的静态方法和实例方法

c++ - 塞类 C++ : TBuf Question

Python奇怪的行为: "+=" creates aliases

python - 从 Python 3 中的列表填充 map 的单行方法

python - 向 tkinter 文本小部件添加高级功能

c++ - OpenCV - moments() 函数中的参数