dynamic attribute within class

前端 未结 1 706
花落未央
花落未央 2021-01-28 15:45

I have situation where (pseudo code):

class MyClass:
   def __init___(self):
      self.varA = [zza, b, c]
      self.varB = [d, e, zzf]
   def process(self):
           


        
相关标签:
1条回答
  • 2021-01-28 16:48

    You could write it like this:

    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
    

    Using setattr and getattr to access attributes by their names.

    Also as the filter does not depend on the items but only the list. It can be hoisted out of the list comprehension and placed outside. It then becomes clear that if "zz" is in the list that the list is emptied.

       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, [])
    
    0 讨论(0)
提交回复
热议问题