简体   繁体   English

Python可继承的函数

[英]Python inheritable functions

Is there a way in Python to either ``type'' functions or for functions to inherit test suites? Python中是否有一种方法可以“输入”函数或继承测试套件的函数? 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. 所以我想要一种方法来将函数标识为某个运算符的实现,以便测试套件可以只获取该运算符的所有函数并通过测试运行它们。

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. 我最初的想法是使用类和子类,但是为了这个目的,类语法有点笨拙,因为我首先要创建一个类的实例,然后才能将它作为函数调用...除非有一个允许init返回None以外的类型的方法。

Can metaclasses or objects be used in this fashion? 可以以这种方式使用元类或对象吗?

Functions are first class objects in Python and you can treat them as such, eg add some metadata via setattr : 函数是Python中的第一类对象,您可以将它们视为对象,例如通过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

I apologize, as I cannot comment but just to clarify you stated " I would first have to create an instance of the class before I could call it as a function... " Does this not accomplish what you are trying to do? 我道歉,因为我不能发表评论,但只是为了澄清你说“我首先必须创建一个类的实例才能将其称为函数......”这不能完成你想要做的事情吗?

    class functionManager:

        def __init__(testFunction1 = importedTests.testFunction1):
           self.testFunction1() = testFunction1


    functionManager = functionManager()

Then just include the line from functionManagerFile import functionManager wherever you wanna use it? 然后只需要包含from functionManagerFile import functionManager的行from functionManagerFile import functionManager无论你想在哪里使用它?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM