为什么我的代码出错,与'@property'有关

0 投票
1 回答
616 浏览
提问于 2025-04-15 17:23

我用的是Python 2.5,我想知道当平台是Python 2.5或Python 2.6时,如何修改下面的代码。

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

a=C()
print a.x#error

谢谢


谢谢,亚历克斯,我觉得在你的例子中,property必须有三个参数。

但是,我见过一个代码,它的'property'只用了一个参数,为什么这样也能工作呢?

class SortingMiddleware(object):
    def process_request(self, request):
        request.__class__.field = property(get_field)
        request.__class__.direction = property(get_direction)

1 个回答

4

Python 2.5不支持.setter.deleter这两个属性装饰器;这两个功能是在Python 2.6中才引入的。

如果你想让代码在这两个版本上都能运行,可以这样写:

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

    def _get_x(self):
        """I'm the 'x' property."""
        return self._x
    def _set_x(self, value):
        self._x = value
    def _del_x(self):
        del self._x
    x = property(_get_x, _set_x, _del_x)

撰写回答