简体   繁体   中英

Python inheritable functions

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.

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?

Functions are first class objects in Python and you can treat them as such, eg 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

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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