Python - 可以将相同的属性逻辑应用于多个属性吗?

有没有办法将相同的属性逻辑应用于类中的一组属性?例如,我想申请相同的@attr1.setter装饰器attr2,attr3以及attr4不必定义每个属性的属性。


class Sample:

    def __init__(self):

        self.attr1 = None

        self.attr2 = None

        self.attr3 = None

        self.attr4 = None


    @property

    def attr1(self):

        return self.__attr1


    @attr1.setter

    def attr1(self, val):

        if val < 0:

            self.__attr1 = 0

        else:

            self.__attr1 = val


翻过高山走不出你
浏览 192回答 2
2回答

九州编程

只需为此创建您自己的描述符:class MyDescriptor:&nbsp; &nbsp; def __set_name__(self, owner, name):&nbsp; &nbsp; &nbsp; &nbsp; self.name = f'_{name}'&nbsp; &nbsp; def __get__(self, instance, owner):&nbsp; &nbsp; &nbsp; &nbsp; return getattr(instance, self.name)&nbsp; &nbsp; def __set__(self, instance, val):&nbsp; &nbsp; &nbsp; &nbsp; if val is None:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setattr(instance, self.name, None)&nbsp; &nbsp; &nbsp; &nbsp; elif val < 0:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setattr(instance, self.name, 0)&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setattr(instance, self.name, val)class Sample:&nbsp; &nbsp; attr1 = MyDescriptor()&nbsp; &nbsp; attr2 = MyDescriptor()&nbsp; &nbsp; attr3 = MyDescriptor()&nbsp; &nbsp; attr4 = MyDescriptor()&nbsp; &nbsp; def __init__(self):&nbsp; &nbsp; &nbsp; &nbsp; self.attr1 = None&nbsp; &nbsp; &nbsp; &nbsp; self.attr2 = None&nbsp; &nbsp; &nbsp; &nbsp; self.attr3 = None&nbsp; &nbsp; &nbsp; &nbsp; self.attr4 = None现在,在行动:In [3]: s = Sample()In [4]: s.attr1 = -99In [5]: s.attr1Out[5]: 0In [6]: s.attr2In [7]: s.attr2 = 10In [8]: s.attr2Out[8]: 10In [9]: s.attr2 = -1In [10]: s.attr2Out[10]: 0请参阅描述符 HOWTO和一些更相关的文档请注意,我None在您的 setter 逻辑中加入了可能性(您的代码会TypeError在实例初始化时引发 a ,因为 setter 检查 if None < 0)。另请注意,您可能不想使用双下划线名称修饰(这并不意味着 private),因此我使用传统的单下划线来表示不属于公共 api 的变量。使用双下划线名称修改会使这里的事情复杂化。

温温酱

您可以覆盖__getattr__和__setattr__以按照您希望的方式行事。这样你就不需要定义任何私有变量,也不需要初始化任何成员变量。class Sample:&nbsp; &nbsp; def __getattr__(self, attr):&nbsp; &nbsp; &nbsp; &nbsp; return self.__dict__.get(attr)&nbsp; &nbsp; def __setattr__(self, attr, val):&nbsp; &nbsp; &nbsp; &nbsp; if val is not None and val < 0:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.__dict__[attr] = 0&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.__dict__[attr] = vals = Sample()print(s.attr1) # Nones.attr1 = 10print(s.attr1) # 10s.attr1 = -10print(s.attr1) # 0s.attr1 = Noneprint(s.attr1) # None
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python