Python:多种属性,一个设置器/获取器 [英] Python: multiple properties, one setter/getter
本文介绍了Python:多种属性,一个设置器/获取器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请考虑以下类定义
class of2010(object):
def __init__(self):
self._a = 1
self._b = 2
self._c = 3
def set_a(self,value):
print('setting a...')
self._a = value
def set_b(self,value):
print('setting b...')
self._b = value
def set_c(self,value):
print('setting c...')
self._c = value
a = property(fset=self.set_a)
b = property(fset=self.set_b)
c = property(fset=self.set_c)
请注意,set_[a|b|c]()
会执行相同的操作.有没有一种方法可以定义:
note that set_[a|b|c]()
do the same thing. is there a way do define:
def set_magic(self,value):
print('setting <???>...')
self._??? = value
一次并按如下所示将其用于a,b,c
once and use it for a,b,c as follows
a = property(fset=self.set_magic)
b = property(fset=self.set_magic)
c = property(fset=self.set_magic)
推荐答案
def attrsetter(attr):
def set_any(self, value):
setattr(self, attr, value)
return set_any
a = property(fset=attrsetter('_a'))
b = property(fset=attrsetter('_b'))
c = property(fset=attrsetter('_c'))
这篇关于Python:多种属性,一个设置器/获取器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文