我已经搜索了这个,但我看到的结果却恰恰相反:将多个装饰器应用于单个函数。
我想简化这种模式。有没有办法将这个单个装饰器应用于多个功能?如果没有,我怎样才能重写上述内容以减少重复?
from mock import patch
@patch('somelongmodulename.somelongmodulefunction')
def test_a(patched):
pass # test one behavior using the above function
@patch('somelongmodulename.somelongmodulefunction')
def test_b(patched):
pass # test another behavior
@patch('somelongmodulename.somelongmodulefunction')
def test_c(patched):
pass # test a third behavior
from mock import patch
patched_name = 'somelongmodulename.somelongmodulefunction'
@patch(patched_name)
def test_a(patched):
pass # test one behavior using the above function
@patch(patched_name)
def test_b(patched):
pass # test another behavior
@patch(patched_name)
def test_c(patched):
pass # test a third behavior
答案 0 :(得分:3)
如果你想制作" long"函数只调用一次并用结果装饰所有三个函数,就这样做。
//node.h
struct node{
int val;
struct node* next;
};
int length(struct node *);
struct node* push(struct node *, int);
void print(struct node *, int);
//node.c
#include "./node.h"
#include<stdlib.h>
#include<stdio.h>
int length(struct node *current){
if(current->next != NULL)
return 1 + length(current->next);
else
return 1;
}
struct node* push(struct node *head, int num){
struct node *temp = malloc(sizeof(struct node));
temp->val = num;
temp->next = head;
head = temp;
return head;
}
void print(struct node* head, int size){
printf("The list is %i", size);
printf(" long \n");
struct node* temp;
temp = head;
while(temp != NULL){
printf("%d", temp->val);
printf(" ");
temp = temp->next;
}
printf(" \n");
}
//main program
#include "./node.h"
#include<stdlib.h>
#include<stdio.h>
int main(){
char ans;
int num;
struct node* head = NULL;
do{
printf("Enter a integer for linked list: ");
scanf("%d", &num);
head = push(head, num);
printf("Add another integer to linked list? (y or n) ");
scanf("%1s", &ans);
}while(ans == 'y');
print(head, length(head));
return 0;
}
答案 1 :(得分:2)
如果您想获得幻想,可以修改globals()
。下面的一般想法应该有效。
test_pattern = re.compile(r'test_\w+')
test_names = [name for name in globals().keys() if test_pattern.match(name)]
for name in test_names:
globals()[name] = decorate(globals()[name])