我刚开始在Python中使用装饰器,我不确定如何正确使用它.
假设我有这段代码:
def viable_decorator(fonction_viable):
def viable(sequences, pos):
codons = [seq[pos:pos+3] for seq in sequences]
return not any("-" in codon for codon in codons)
return viable
@viable_decorator
def viable(sequences, pos):
codons = [seq[pos:pos+3] for seq in sequences]
return not all("-" in codon for codon in codons)
sequncess = ["---aaacacaacaacaaat",
"------aaacacacac---",
"aaggcggaggcgg---ggg",]
print viable(sequences, 0)
我的目标是能够根据情况使用函数possible()的两个版本.这是装饰者应该如何工作的?如果是,我如何确定alive()函数的选择?因为现在,在这段代码中,总是调用装饰器.
提前致谢.
解决方法:
Is this how decorators are supposed to work ?
不.通常装饰者应该“装饰”原始功能,或者为原始功能添加一些额外的东西.不要创建一个与装饰的无关的新的.
在您的特定情况下:
def viable_decorator(fonction_viable):
def viable(sequences, pos):
codons = [seq[pos:pos+3] for seq in sequences]
return not any("-" in codon for codon in codons)
return viable
装饰者甚至不使用装饰函数fonction_viable.当然,这样做在语法上是有效的,但它不是正如名称所暗示的装饰器所应该做的那样.
标签:python,python-decorators
来源: https://codeday.me/bug/20190527/1162498.html