我正在寻找一种方法来避免使用@property decorator重复结构相同的getter/setter定义。例如:
class foo:
def __init__(self,length):
self.length=length
# length
@property
def length(self):
return self._length
@length.setter
def length(self, val):
# do some checks here (e.g. for units, etc.) (same as in the class below)
self._length = val
class bar:
def __init__(self,width):
self.width=width
# width
@property
def width(self):
return self._width
@width.setter
def width(self, val):
# do some checks here (e.g. for units, etc.)(same as in the class above)
self._width = val
类bar中的属性width和类foo中的属性length在结构上具有相同的setter,因此我想定义一个可以应用于这些属性的通用setter。 然而,我不知道如何达到预期的行为?也许是二级装潢师
非常感谢您的帮助:)
也许您可以使用python描述符协议来实现您想要的
所以我想我可以给你一个最新的结果。因此,我之所以要寻找这样的解决方案,也是因为我希望通过属性的setter,为属性合并单元跟踪,并能够解析单元值数据
对我来说,这个解决方案似乎相当简洁,但也许我在监督一些事情。。。 如果您对此有任何意见,请随时发表评论:)
最终
@property
只返回一个实现描述符协议的对象,因此您可以很容易地实现这样的事情:这是一个简单的例子,您可能希望熟悉descriptor protocol和装饰器,以使其更完整,并可能以更可重用的方式对其进行修饰,但只要将属性设置为实现
__get__
和__set__
的对象,您就可以根据自己的喜好对其进行自定义。请参阅https://stackoverflow.com/a/17330273/476以获得良好的概述注意
__set_name__
仅在Python 3.6之后可用;在旧版本中,您需要显式地通过__init__
传递名称,如bar = ReusableProperty('bar')
相关问题 更多 >
编程相关推荐