简体   繁体   English

在python 2.5.1或更早版本中使用property和setter

[英]Using property and setter in python 2.5.1 or older

How can I use @property.setter which was not implementet in Python 2.5.1. 我如何使用@property.setter在Python 2.5.1中没有实现。

Here is a example how to do it in newer versions of python. 这是一个在新版本的python中如何执行此操作的示例。
Since I am using an older version of Python I can't really use this code. 由于我使用的是旧版本的Python,因此我无法真正使用此代码。

class Info(object):

    def __init__(self):
        self.x = None

    @property
    def x(self): 
        return self.x

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

test = Info()
test.x = "It works!"
print(test.x)

Output: It works! 输出:有效!

Here is one way to do it. 这是一种方法。 You can use __get__ and __set__ as a replacement. 您可以使用__get____set__作为替代。 This can be used in 2.5.1 or older versions of Python 可以在2.5.1或更早版本的Python中使用

class Info(object):

        def __init__(self):
            self.x = None

        class x:
            def __init__(self):
                pass

            def __get__(self, instance):
                return instance.x

            def __set__(self, instance, value):
                instance.x = value


    test = Info()
    test.x = "It works too, in 2.5.1"

    print(test.x)

Output: It works too, in 2.5.1 输出:在2.5.1中也可以使用

property in 2.5 support fget, fset and fdel, but not the @property.setter decorator. 2.5中的property支持fget,fset和fdel,但不支持@ property.setter装饰器。

So, two solution: 因此,两种解决方案:

  1. don't use property as a decorator but as a function; 不要将property用作装饰器,而应将其用作函数;
  2. create a derivated class adding them. 创建一个添加它们的派生类。

First solution: 第一个解决方案:

class Info(object):
    def __init__(self):
        self._x = None
    def get_x(self): 
        return self._x
    def set_x(self, value): 
        self._x = value
    x = property(get_x, set_x)

Second solution: 第二种解决方案:

class _property(__builtin__.property):
    def getter(self, fget):
        return __builtin__.property(fget, self.fset, self.fdel)
    def setter(self, fset):
        return __builtin__.property(self.fget, fset, self.fdel)
    def deleter(self, fdel):
        return __builtin__.property(self.fget, self.fset, fdel)

try:
    property.getter
except AttributeError:
    property = _property

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM