Python-使用不同的参数重载相同的函数
我有一个功能,设置功能,并希望有两个版本的它。一种是将所有特征分割成单词和短语,另一种是将已经分割的单词和短语作为参数Python-使用不同的参数重载相同的函数,python,overloading,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 ' '
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,但对于一些小案例来说,这是一种过分的做法。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\u功能(features=features)
或set\u功能(words=words,phrases=phrases)
函数参数本身不能重载,但可以使用关键字参数模拟此行为。有点恼人的是,您必须处理有效性检查(即,用户不能同时通过功能
和单词
和阶段
)。例如:
拥有
单词
、短语
和功能
参数,并为它们提供默认值无
,然后检查在处理之前通过了什么。?或者使用*args、**kwargs构造允许接受任意参数。为什么要重载名称?这两种方法具有不同的功能,在数据处理或语言学方面没有真正的概念重叠;我只是看到一个命名问题。如果您提供的数据可能有不同的表示形式,但结果是相同的,那么方法重载是有意义的。我不明白为什么要使用方法重载。关于:设置功能(短语=短语)
?我认为SortedSet
接受None
,但set
不接受。这是假设允许无
是有意义的。。。
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)