如何简化这种类似的ifs

时间:2012-07-05 15:46:17

标签: python

我试图弄清楚如何简化这段代码。每个if条件的逻辑基本相同,所以我想摆脱重复的ifs:

      if "video_codec" in profile:
          self.video_codec = profile["video_codec"]
      if "resolution_width" in profile:
          self.resolution_width = profile["resolution_width"]
      if "resolution_height" in profile:
          self.resolution_height = profile["resolution_height"]
      if "ratio" in profile:
          self.ratio = profile["ratio"]
      if "video_bitrate" in profile:
          self.video_bitrate = profile["video_bitrate"]
      if "profile" in profile:
          self.profile = profile["profile"]
      if "audio_codec" in profile:
          self.audio_codec = profile["audio_codec"]
      if "audio_channels" in profile:
          self.audio_channels = profile["audio_channels"]
      if "audio_bitrate" in profile:
          self.audio_bitrate = profile["audio_bitrate"]

我希望这可以用3-4行代替我的18行。

2 个答案:

答案 0 :(得分:10)

for key, value in profile.iteritems():
    setattr(self, key, value)

应该做你想做的事

答案 1 :(得分:7)

如果您只想将profile中的所有键/值对复制到self中的属性,则可以使用以下内容:

self.__dict__.update(profile)

如果profile中有一些您不想复制的项目,则可以使用以下内容:

for attr in ("video_codec", "resolution_width", "resolution_height", "video_bitrate", 
             "ratio", "profile", "audio_codec", "audio_channels", "audio_bitrate"):
    if attr in profile: 
        setattr(self, attr, profile[attr])