gpt4 book ai didi

python - 我可以对多个属性使用相同的@property setter 吗?

转载 作者:太空狗 更新时间:2023-10-30 00:14:04 25 4
gpt4 key购买 nike

我的类有许多属性都需要使用相同类型的 setter:

@property
def prop(self):
return self._prop

@prop.setter
def prop(self, value):
self.other_dict['prop'] = value
self._prop = value

有没有一种简单的方法可以将此 setter 结构应用于许多属性,而无需为每个属性编写这两个方法?

最佳答案

您可以使用 descriptor 来实现它,即如下:

class MyProperty(object):

def __init__(self, name):
self.name = name

def __get__(self, instance, owner):
if instance is None:
return self
else:
# get attribute from the instance
return getattr(instance, '_%s' % self.name) # return x._prop

def __set__(self, instance, value):
# set attribute and the corresponding key in the "remote" dict
instance.other_dict[self.name] = value # x.other_dict["prop"] = value
setattr(instance, '_%s' % self.name, value) # x._prop = value

并按如下方式使用它们:

class MyClass(object):

prop = MyProperty("prop")
another_prop = MyProperty("another_prop")

附带说明:可能值得考虑您是否真的需要复制属性值。通过从 other_dict 返回相应的值,您可以轻松地完全摆脱 _prop 属性。这也避免了由存储在 dict 和类实例中的不同值引起的潜在问题——这在您当前的方案中很容易发生。

关于python - 我可以对多个属性使用相同的@property setter 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30868217/

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