gpt4 book ai didi

python - 在 python 2.5.1 或更早版本中使用属性和 setter

转载 作者:行者123 更新时间:2023-12-01 05:03:44 26 4
gpt4 key购买 nike

如何使用 Python 2.5.1 中未实现的 @property.setter

这是一个如何在较新版本的 python 中执行此操作的示例。
由于我使用的是较旧版本的 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!

最佳答案

2.5 中的 property 支持 fget、fset 和 fdel,但不支持 @property.setter 装饰器。

所以,有两种解决方案:

  1. 不要将属性用作装饰器,而应将其用作函数;
  2. 创建一个派生类添加它们。

第一个解决方案:

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)

第二个解决方案:

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

关于python - 在 python 2.5.1 或更早版本中使用属性和 setter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25477612/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com