2013-01-16 4 views
1

이 간단한 코드 예제에서는 .do()가 호출 될 때마다 조건 목록을 처리해야 클래스를 처리해야한다는 문제가 있습니다 예상대로 작동합니다. 이것은 매우 효율적이지 않으며, 나는 다른 방법이 있다는 것을 확신하지만 그것에 손가락을 대지 못합니다."동적"코드를 사용하여이 예제의 조건부 오버 헤드를 줄이는 방법

이 클래스를 좀 더 효율적으로 동일하게 동작시키기 위해 할 수있는 방법은 무엇입니까?

class translate(): 
    def __init__(self, EN=True, FR=False, DE=False, SP=False): 
     self.EN=EN 
     self.FR=FR 
     self.DE=DE 
     self.SP=SP 

    def do(self, word): 
     if self.EN: 
      self.en(word) 
     if self.FR: 
      self.fr(word) 
     if self.DE: 
      self.de(word) 
     if self.SP: 
      self.sp(word) 

    def en(self, word): 
     print "In English: %s"%(word) 

    def fr(self, word): 
     print "In French: %s"%(word) 

    def de(self, word): 
     print "In German: %s"%(word)  

    def sp(self, word): 
     print "In Spanish: %s"%(word) 

tr=translate(FR=True) 
tr.do("blah") 

내가 지금 이런 일하지만 난 단지 한 언어를 할 수 있었다 : 원래 코드에서

class translate(): 
    def __init__(self, EN=False, FR=False, DE=False, SP=False): 
     if EN: 
      self.do=self.en 
     elif FR: 
      self.do=self.fr 
     elif DE: 
      self.do=self.de 
     elif SP: 
      self.do=self.sp 
     else: 
      self.do=self.unkown 

    def en(self, word): 
     print "In English: %s"%(word) 

    def fr(self, word): 
     print "In French: %s"%(word) 

    def de(self, word): 
     print "In German: %s"%(word)  

    def sp(self, word): 
     print "In Spanish: %s"%(word) 

    def unknown(self, word): 
     print "Unknown: %s"%(word) 

tr=translate(FR=True) 
tr.do("blah") 
+3

이 사전을 사용하여 ... – mgilson

+0

mgilson 잘, 당신은이 사전의 키로 (언어, 단어)를 사용할 수 있습니다. –

+0

내가 아는 한, 그는 한 번 여러 언어로 번역 할 수 있기를 원합니다. – Michael

답변

4

do 하나 이상의 변환 메서드를 호출 할 수 있습니다. 당신은 실제로 어디서든 번역을 저장하지 않습니다

In English: blah 
In French: blah 
+1

'do'는 객체를 직접 호출하기 위해'__call__'이라는 이름을 붙일 수 있습니다. – jfs

0

class Translate(): 
    def __init__(self, EN=True, FR=False, DE=False, SP=False): 
     self.translators = [method for lang, method in 
          zip((EN, FR, DE, SP), 
           (self.en, self.fr, self.de, self.sp)) 
          if lang] 

    def do(self, word): 
     for method in self.translators: 
      method(word) 

    def en(self, word): 
     print "In English: %s" % (word) 

    def fr(self, word): 
     print "In French: %s" % (word) 

    def de(self, word): 
     print "In German: %s" % (word) 

    def sp(self, word): 
     print "In Spanish: %s" % (word) 

tr = Translate(FR=True) 
tr.do("blah") 

당신이 단지에가는, 그래서 산출 : 따라서, 우리는 번역 방법 목록의 트랙 (혹은 세트)를 유지해야 객체가 초기화 된 각 언어에 대해 단어를 입력 할 때 철자로 표시된 단어를 인쇄하십시오. 번역을 저장하고 검색 할 수있는 시스템이 필요하며 이는 주어진 단어에 대해 번역이 설정된 모든 값을 제공합니다. , 또는

class WordTranslationMap(dict): 

    def __init__(self): 
     dict.__init__(self, languages) 
     for language in languages: 
      self[language] = None 

    def all(self): 
     for language, translation in self.iteritems(): 
      if translation is not None: 
       yield (language, translation) 

class TranslationDictionary(dict): 

    def __init__(supported_languages=['EN', 'SP', 'FR', 'DE']): 
     dict.__init__(self) 
     self.supported_languages = supported_languages 

    def __getitem__(self, key): 
     try: 
      return dict.__getitem__(self, key) 
     except KeyError: 
      word = WordTranslationMap(self.supported_languages) 
      self[key] = word 
      return word 

words = TranslationDictionary() 
words['hello']['EN'] = 'hello' 
words['hello']['FR'] = 'bonjour' 
for translation in words['hello'].all: 
    print translation 

를 모국어로 구성 :이 작동 할

class WordToken(object): 
    def __init__(value, translation_dictionary, word_id=None): 
     self.value = value 
     self.word_id = translation_dictionary.next_id.next() if word_id is None else word_id 
     self.translation_dictionary= translation_dictionary 

    def __getitem__(self, key): 
     try: 
      return self.translation_dictionary[key][self.word_id] 
     except KeyError: 
      return None 

    def __setitem__(self, key, value): 
     self.translation_dictionary[key][self.word_id] = value 

    def all(self): 
     for language, translations in self.translation_dictionary.language_dictionaries.iteritems(): 
      try: 
       yield (language, str(translations[self.word_id])) 
      except KeyError: 
       pass 

    def __str__(self): 
     return self.value 

class LanguageDictionary(dict): 

    def __init__(self, translation_dictionary): 
     dict.__init__(self) 
     self.translation_dictionary = translation_dictionary 

    def add_word(self, word): 
     word = WordToken(word, self.translation_dictionary) 
     self[word.word_id] = word 

    def __setitem__(self, key, value): 
     try: 
      if value.word_id != key: 
       raise ValueError('Tried to set translation to word object that does not match language dictionary key.') 
     except AttributeError: 
      value = WordToken(value, self.translation_dictionary, key) 
     dict.__setitem__(self, key, value) 

class TranslationDictionary(object): 

    def __init__(self): 
     self.next_id = itertools.count(start=0, step=1) 
     self.language_dictionaries = defaultdict(LanguageDictionary) 

    def __getitem__(self, key): 
     return self.language_dictionaries[key] 

dictionary = TranslationDictionary() 
dictionary['EN'].add_word('hello') 
dictionary['EN']['hello']['FR'] = 'bonjour' 
for translation in dictionary['EN']['hello'].all(): 
    print translation 
+0

"실제로 번역을 저장하지 않습니다."나는 알고 있습니다. 불행히도 제 목적에 혼란스러운 예제를 사용했다고 생각합니다. –

관련 문제