Python - 使用不同的参数

时间:2018-03-21 20:24:18

标签: python overloading

我有一个功能设置功能,并希望有两个版本的功能。一个接受所有功能并将它们分成单词和短语,第二个接收已经拆分的单词和短语作为参数

def set_features_2(self, words, phrases):
    self.vocabulary = set(words)
    self.phrases = SortedSet(phrases)

def set_features(self, features):
    phrases = [f for f in features if ' ' in f]
    words = [f for f in features if f not in phrases]
    self.set_features_2(words, phrases)

删除此重复的最简单方法是什么?它们都应该被称为“set_features”,但它们都接收一组不同的参数。 我知道可以使用args和kwargs,但这对于诸如琐碎的案例来说是一种过度杀伤。

2 个答案:

答案 0 :(得分:2)

您不能重载函数参数本身,但您可以使用关键字参数模拟此行为。稍微烦人的部分是您必须处理有效性检查(即,用户未同时通过featureswords以及phases)。 E.g:

def set_features(self, features = None, words = None, phrases = None):
    if features: 
        if words or phrases:
            raise ValueError('Either pass features or words and phrases')
        else:
            phrases = [f for f in features if ' ' in f]
            words = [f for f in features if f not in phrases]

    self.vocabulary = set(words)
    self.phrases = SortedSet(phrases)

答案 1 :(得分:1)

Python允许使用默认参数。

def set_features(self, features=None, words=None, phrases=None):
    if features is not None:
        phrases = [f for f in features if ' ' in f]
        words = [f for f in features if f not in phrases]

    self.vocabulary = set(words)
    self.phrases = SortedSet(phrases)

然后,您可以使用set_features(features=features)set_features(words=words, phrases=phrases)

来调用它