2014-10-08 28 views
0

好吧讓我重組這個更理論 - 我如何分隔一個函數內的重複任務。函數內的函數 - 好主意?

下面是這種情況:

def some_class: 
    def out_fxn(): 
     self.some_vars being used here 
     for each value in some dict: 
      if entry has type_A: 
       get value, dict_index from entry 
       some_function(my_dict, dict_key, value) 
      if entry has type_B: 
       get value, dict_index from entry 
       some_function(my_dict, dict_key, value) 
      if entry has type_C: 
       get value, dict_index from entry 
       some_function(my_dict, dict_key, value) 
  1. 類方法?應該some_function(my_dict,dict_index,值)是方法some_class? 它不會使用任何類成員變量,並且與類沒有太大關係
  2. 嵌套函數?應該some_function(my_dict,dict_index,值)是否在out_fxn()? 嵌套功能

注意:我可以遍歷ABC,相應地分配值,但我只想知道是否有一種方法可以使用函數來完成此操作。

+0

這裏有一些紅旗 - 類型的字典沒有指標,一。而且你不可能*有*在A,B和C上依次運行some_function()...「。這有一個非常時髦的代碼氣味,但不知道你在做什麼的具體細節,沒有辦法告訴你如何重構它。 – roippi 2014-10-08 21:39:12

+0

對於從字面上看沒有額外的麻煩,您可以在for循環中使用語法上有效的代碼來避免模糊。 「入口」與「每個值」相同嗎?將它寫爲'在some_dict.items()中輸入:'不會含糊不清。那麼什麼是'value,dict_index',它與入口有什麼關係?它們是屬性嗎?它們對於每種情況都是一樣的還是不同的? my_dict與「some dict」相同嗎? – chthonicdaemon 2014-10-09 04:54:09

回答

1
class some_class(object): 
    def out_fxn(self): 
     for entry in some_dict: 
      for entry_type in ["type_A", "type_B", "type_C"]: 
       entry_value, entry_key = self.get_entry_stuff(entry_type) 
       self.some_fiunction(some_dict, entry_key, entry_value) 

    def some_function(self, my_dict, dict_key, value): 
     pass 

    def get_entry_stuff(self, entry_type): 
     if entry_type == "type_A": 
      return "a value", "a key" 
     elif entry_type == "type_B": 
      return "b value", "b key" 
     elif entry_type == "type_C": 
      return "c value", "c key" 
     else: 
      raise ValueError("I don't know about type: %s" % repr(entry_type)) 
+0

所以我讓他們類方法,即使他們是非常具體到我的功能? – rtindru 2014-10-09 04:40:45

+1

許多Python開發人員(包括我自己)將所有內容放在課堂上。當您決定繼承某些功能時,它們會爲您提供更大的靈活性。爲了創建未綁定的函數組,請查看classmethod和staticmethod裝飾器http://stackoverflow.com/questions/12179271/python-classmethod-and-staticmethod-for-beginner – ErlVolton 2014-10-09 14:13:10

1

您可以用循環替換的if-else塊:

for typei in [typeA, typeB, typeC]: 
    if entry contains typei: 
     run_function(entry)