Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

python - dynamic attribute within class

I have situation where (pseudo code):

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

What I would like to have is something more elegant, where I could pass variable to process through definition:

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

But that would mean it has to dynamically change attribute within that def ? How can I approach it ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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, [])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...