Python 在本例中,如何使用“减少条件开销”;“动态”;代码

Python 在本例中,如何使用“减少条件开销”;“动态”;代码,python,Python,在这个简单的代码示例中,我遇到了一个问题:每次调用.do()时,都需要处理一系列条件,才能使类按预期的方式运行。这不是很有效,我很确定还有另一种方法,但我无法确定 我可以用什么方法使这个类的行为更加相同,但效率更高 class translate(): def __init__(self, EN=True, FR=False, DE=False, SP=False): self.EN=EN self.FR=FR self.DE=DE

在这个简单的代码示例中,我遇到了一个问题:每次调用.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")
我可以这样做,但我只能做1种语言:

    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")

在原始代码中,
do
可以调用多个翻译方法。 因此,我们应该跟踪翻译方法的列表(或者一套):

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")
屈服

In English: blah
In French: blah

在原始代码中,
do
可以调用多个翻译方法。 因此,我们应该跟踪翻译方法的列表(或者一套):

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")
屈服

In English: blah
In French: 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

实际上,您并没有将翻译存储在任何地方,所以您只需要在为每个语言输入单词时,按拼写打印该单词,而对象是针对这些语言初始化的。您需要一个允许您存储和检索翻译的系统,该系统将为您提供为给定单词设置翻译的所有值。这将有助于:

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

mgilson是对的,你可以使用(语言,单词)作为这本词典的关键字。据我所知,他希望能够一次翻译几种语言。如果你使用
(lang,word)
作为词典关键字,那么实际上很难按单词或语言提取数据,因为这样做,您需要遍历完整的键列表。在这种情况下,结构化数据会更好地工作,因为使用模式是获取给定单词的所有翻译。很抱歉,我的“翻译示例”正在引导您朝着这个方向前进,这不是我的意图。我的目的是能够以这样的方式初始化该类:我不需要.do()函数中的条件。mgilson是对的,您可以使用(语言,单词)作为该词典的键。据我所知,他希望能够一次翻译几种语言。如果您使用
(lang,word)
作为词典键,通过单词或语言提取数据变得非常困难,要做到这一点,您需要遍历完整的键列表。在这种情况下,结构化数据会更好地工作,因为使用模式是获取给定单词的所有翻译。很抱歉,我的“翻译示例”正在引导您朝着这个方向前进,这不是我的意图。我的目的是能够以这样一种方式初始化类:我不需要.do()函数中的条件。
do
可以命名为
\uuuu call\uuuu
,直接调用对象。
do
可以命名为
\uuuu call\uuuu
,直接调用对象。“您实际上并没有在任何地方存储翻译。”我知道:)不幸的是,我想我用了一个令人困惑的例子。我知道:)不幸的是,我用了一个令人困惑的例子。