属性设置器在python 2中不起作用

时间:2015-11-29 22:31:48

标签: python properties setter

我编写了一个Python类,但是setter似乎没有用。

来自https://docs.python.org/2/library/functions.html#property

  

属性对象具有可用的getter,setter和deleter方法   装饰器,用相应的属性创建属性的副本   访问器功能设置为装饰功能。这是最好的   用一个例子解释:

class C(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

我的(示例)课程:

# -*- coding: utf-8 -*-

class PropertyTest:
    def __init__(self):
        self.prop_ = 5

    @property
    def prop(self):
        print "Getting prop plus one"
        return self.prop_ + 1

    @prop.setter
    def prop(self, propValue):
        print "Assigning prop to " + propValue
        self.prop_ = propValue

t = PropertyTest()
print t.prop
t.prop = 10
print t.prop

预期产出:

  

获得道具加一个

     

6

     

将道具分配给10

     

获得道具加一个

     

11

但我得到的是:

  

获得道具加一个

     

6

     

10

我做错了什么?

0 个答案:

没有答案
相关问题