ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-06-28 14:45:02  阅读:181  来源: 互联网

标签:python getter-setter python-decorators


我的类有许多属性都需要使用相同类型的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,getter-setter,python-decorators
来源: https://codeday.me/bug/20190628/1316551.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有