类中的动态属性

时间:2016-11-23 02:54:19

标签: python

我的情况是(伪代码):

class MyClass:
   def __init___(self):
      self.varA = [zza, b, c]
      self.varB = [d, e, zzf]
   def process(self):
      self.varA = ["zz" + w for w in self.varA if "zz" not in self.varA]
      self.varB = ["zz" + w for w in self.varB if "zz" not in self.varB]
      print varA, varB

我想要的是更优雅的东西,我可以通过定义传递变量来处理:

class MyClass:
   def __init___(self):
      self.varA = [zza, b, c]
      self.varB = [d, e, zzf]
   def addZZ(list):
      return list = ["zz" + w for w in list if "zz" not in list]
   def process(self):
      self.addZZ(varA)
      self.addZZ(varB)
      print self.varA, self.varB

但这意味着它必须动态更改该def中的属性?我该怎么办呢?

1 个答案:

答案 0 :(得分:0)

你可以这样写:

class MyClass:
   def __init___(self):
      self.varA = [zza, b, c]
      self.varB = [d, e, zzf]
   def addZZ(varname):
      _list = getattr(self, varname)
      setattr(self, varname, ["zz" + w for w in _list if "zz" not in _list])
   def process(self):
      self.addZZ('varA')
      self.addZZ('varB')
      print self.varA, self.varB

使用setattrgetattr按名称访问属性。

此外,过滤器不依赖于项目而仅依赖于列表。它可以从列表理解中提升并放在外面。然后很明显,如果列表中的"zz"清空,则列表清空。

   def addZZ(varname):
      _list = getattr(self, varname)
      if "zz" not in _list:
          setattr(self, varname, ["zz" + w for w in _list])
      else:
          setattr(self, varname, [])