在下面的 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/