Python inheritable functions

吃可爱长大的小学妹 提交于 2019-12-06 02:42:36

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

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?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!