Python可继承的函数 [英] Python inheritable functions

查看:477
本文介绍了Python可继承的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中有没有一种方法能够键入函数或者用于
继承测试套件的函数?我正在做一些工作,用各种标准评估不同函数的几个不同的
实现(对于
示例,我可以根据
数组大小和内存要求的速度来评估不同的排序函数)。我希望b $ b能够自动化功能测试。所以我想
就像一种方法来识别一个函数作为
a某个运算符的一个实现,这样测试套件就可以获取所有函数
,它们是该运算符的实现并通过它运行它们
测试。

Is there a way in Python to either ``type'' functions or for functions to inherit test suites? I am doing some work evaluating several different implementations of different functions with various criteria (for example I may evaluate different sort functions based on speed for the array size and memory requirements). And I want to be able to automate the testing of the functions. So I would like a way to identify a function as being an implementation of a certain operator so that the test suite can just grab all functions that are implementation of that operator and run them through the tests.

我最初的想法是使用类和子类,但是为了这个目的,类
语法有点笨拙,因为我首先要有
到在我将其称为
函数之前创建该类的实例...除非有一种方法允许 init 返回除$之外的
a类型。

My initial thought was to use classes and subclasses, but the class syntax is a bit finnicky for this purpose because I would first have to create an instance of the class before I could call it as a function... that is unless there is a way to allow init to return a type other than None.

可以这种方式使用元类或对象吗?

Can metaclasses or objects be used in this fashion?

推荐答案

函数是Python中的第一类对象,您可以将它们视为对象,例如通过 setattr <添加一些元数据/ a>:

Functions are first class objects in Python and you can treat them as such, e.g. add some metadata via setattr:

>>> def function1(a):
...     return 1
... 

>>> type(function1)
<type 'function'>

>>> setattr(function1, 'mytype', 'F1')
>>> function1.mytype
'F1'

或使用简单的参数化装饰器相同:

Or the same using a simple parametrized decorator:

def mytype(t):
    def decorator(f):
        f.mytype = t
        return f
    return decorator

@mytype('F2')
def function2(a, b, c):
    return 2

这篇关于Python可继承的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆