property装饰器简化类里实例set,get调用
Posted hell-west-road
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了property装饰器简化类里实例set,get调用相关的知识,希望对你有一定的参考价值。
一般工厂函数使用set方法设置数据,get方法获取结果,例如:
1 from collections import namedtuple 2 3 class Nodes(object): 4 def __init__(self, getIp): 5 self.nodes = None 6 self.node = None 7 self.getIp = getIp 8 9 def setNodes(self, nodes): 10 self.nodes = nodes 11 12 def getNode(self): 13 for i in self.nodes: 14 if i.ip == self.getIp: 15 self.node = i 16 break 17 return self.node 18 19 if __name__ == "__main__": 20 myOpt = namedtuple(‘node‘, ‘ip port user‘) 21 nodes = [ 22 myOpt(‘192.168.1.1‘, 22, ‘guest‘), 23 myOpt(‘192.168.1.2‘, 22, ‘guest‘), 24 ] 25 myNode = Nodes(‘192.168.1.1‘) 26 myNode.setNodes(nodes) 27 print(myNode.getNode())
set和get方法两者没有对应关系相互独立,另外一个坏处,随着类函数越多set和get的方法越多,不利于阅读
property:
1 from collections import namedtuple 2 3 class Nodes(object): 4 def __init__(self, getIp): 5 self.nodes = None 6 self.node = None 7 self.getIp = getIp 8 9 @property 10 def getNodes(self): 11 for i in self.nodes: 12 if i.ip == self.getIp: 13 self.node = i 14 break 15 return self.node 16 17 @getNodes.setter 18 def getNodes(self, nodes): 19 self.nodes = nodes 20 21 if __name__ == "__main__": 22 myOpt = namedtuple(‘node‘, ‘ip port user‘) 23 nodes = [ 24 myOpt(‘192.168.1.1‘, 22, ‘guest‘), 25 myOpt(‘192.168.1.2‘, 22, ‘guest‘), 26 ] 27 myNode = Nodes(‘192.168.1.1‘) 28 myNode.getNodes = nodes 29 print(myNode.getNodes)
set和get方法对应的方法名相同,设置数据和获取结果调用相同的方法名
以上是关于property装饰器简化类里实例set,get调用的主要内容,如果未能解决你的问题,请参考以下文章
Python中的property类和@property装饰器
Python入门-6面向对象编程:06私有属性和私有方法(实现封装)-@property装饰器-get和set方法-总结