简体   繁体   中英

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.

Here is a example how to do it in newer versions of python.
Since I am using an older version of Python I can't really use this code.

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. This can be used in 2.5.1 or older versions of 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

property in 2.5 support fget, fset and fdel, but not the @property.setter decorator.

So, two solution:

  1. don't use property as a decorator but as a function;
  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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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