Python:为什么描述符不能是实例变量?
假设我定义了这个描述符:
class MyDescriptor(object):
def __get__(self, instance, owner):
return self._value
def __set__(self, instance, value):
self._value = value
def __delete__(self, instance):
del(self._value)
我在这个中使用它:
class MyClass1(object):
value = MyDescriptor()
>>> m1 = MyClass1()
>>> m1.value = 1
>>> m2 = MyClass1()
>>> m2.value = 2
>>> m1.value
2
所以 value
是一个类属性,由所有实例共享。
现在,如果我这样定义:
class MyClass2(object)
value = 1
>>> y1 = MyClass2()
>>> y1.value=1
>>> y2 = MyClass2()
>>> y2.value=2
>>> y1.value
1
在这种情况下,value
是一个实例属性,并且不由实例共享。
为什么当 value
是描述符时它只能是类属性,而当 value
是简单整数时它就变成了实例属性?
Say I define this descriptor:
class MyDescriptor(object):
def __get__(self, instance, owner):
return self._value
def __set__(self, instance, value):
self._value = value
def __delete__(self, instance):
del(self._value)
And I use it in this:
class MyClass1(object):
value = MyDescriptor()
>>> m1 = MyClass1()
>>> m1.value = 1
>>> m2 = MyClass1()
>>> m2.value = 2
>>> m1.value
2
So value
is a class attribute and is shared by all instances.
Now if I define this:
class MyClass2(object)
value = 1
>>> y1 = MyClass2()
>>> y1.value=1
>>> y2 = MyClass2()
>>> y2.value=2
>>> y1.value
1
In this case value
is an instance attribute and is not shared by the instances.
Why is it that when value
is a descriptor it can only be a class attribute, but when value
is a simple integer it becomes an instance attribute?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您忽略了
MyDescriptor
实现中的instance
参数。这就是为什么它看起来是一个类属性。也许你想要这样的东西:You're ignoring the
instance
parameter in your implementation ofMyDescriptor
. That is why it appears to be a class attribute. Perhaps you want something like this:如果您尝试以下代码,将无法工作:
Will not work if you try the code below: