我们如何在不使用“def”关键字的情况下定义函数?

Too*_*one 5 python function python-3.x

可以不使用class关键字来定义类。
下列 ...

get_i = lambda self: self.i    
get_i.__name__ = 'get_i'
get_i.__qualname__ = 'Klass2.get_i'
dct = dict(a=1, i=4, get_i=get_i)    
Klass2 = type('Klass2', (SuperK,), dct)
Run Code Online (Sandbox Code Playgroud)

...产生与以下相同的最终结果:

class Klass1(SuperK):
    a = 1
    i = 4
    def get_i(self):
        return self.i
Run Code Online (Sandbox Code Playgroud)

我们如何为函数做类似的事情?也就是说,我们如何在不使用deforlambda关键字的情况下定义函数?dehf如果以下两段代码创建相同的s ,纯 python 实现会是什么样子foo

def foo(bar):
    bar += 934
    return bar

foo = dehf(blah, blah, blah, blah, [...])
Run Code Online (Sandbox Code Playgroud)

Ara*_*Fey 6

您可以通过调用types.FunctionType构造函数来创建函数。但请记住,此构造函数没有文档记录且特定于实现。在 CPython 中,我们可以通过调用来计算构造函数参数help(types.FunctionType)

class function(object)
 |  function(code, globals[, name[, argdefs[, closure]]])
 |  
 |  Create a function object from a code object and a dictionary.
 |  The optional name string overrides the name from the code object.
 |  The optional argdefs tuple specifies the default argument values.
 |  The optional closure tuple supplies the bindings for free variables.
Run Code Online (Sandbox Code Playgroud)

要创建代码对象,我们可以使用compile

code = compile('print(5)', 'foo.py', 'exec')
function = types.FunctionType(code, globals())

function()  # output: 5
Run Code Online (Sandbox Code Playgroud)