有些东西在我的属性设置器中不起作用

时间:2015-05-14 08:53:04

标签: python numpy

我在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

我将不胜感激任何线索!

1 个答案:

答案 0 :(得分:4)

obj.x[0:2] = numpy.zeros((2,1))并未分配给x

然后x会分配给x