python - 我的属性 setter 有问题

标签 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

如果有任何线索,我将不胜感激!

最佳答案

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

它获取 x 然后分配给 x 的一部分。

关于python - 我的属性 setter 有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30233109/

相关文章:

python - 在 bash 中循环遍历数组

python - 无法将CSV文件数据导入mysql表

c++ - numpy.dot 比原生 C++11 慢 100 倍

python - Pandas 、numpy.where() 和 numpy.nan

python-3.x - 导入tensorflow时出现以下错误: No module named 'numpy.core._multiarray_umath'

python - 如何为对数图创建每十年的点间距

python - 如何修复我的 pandas 数据框中的索引,使其不只将值保持为零,而是增加值?

python - 在 Python 3.3 中是否有一种漂亮的 yield 方法?

python - WindowsError 使用 RotatingFileHandler 和 subprocess.Popen

python - 使用 Python 2.7 安装 numpy Lion?