我在 Python 中测试属性,我发现我的程序中有一个奇怪的行为。假设这段代码:
import numpy
class ClassEnc(object):
def __init__(self):
self.__x = numpy.ones((10,1))
pass
@property
def x(self):
print "getter"
return self.__x
@x.setter
def x(self,val):
print "setter"
self.__x = val
obj = ClassEnc()
obj.x[0:2] = numpy.zeros((2,1))
print obj.x[0:2]
obj.x = 2
鉴于该程序,我希望得到以下输出:
setter #The first asignment
getter #The print access
[ 0. 0. 1.] #The print output
setter #The second asignment
但真正的输出是:
getter #WHY?!
getter
[ 0. 0. 1.]
setter
如果有任何线索,我将不胜感激!
最佳答案
obj.x[0:2] = numpy.zeros((2,1))
没有分配给 x
。
它获取 x
然后分配给 x
的一部分。
关于python - 我的属性 setter 有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30233109/