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

2024-04-26 11:09:36 发布

您现在位置:Python中文网/ 问答频道 /正文

不使用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)

。。。产生的最终结果与:

^{pr2}$

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

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

foo = dehf(blah, blah, blah, blah, [...])

Tags: lambda函数nameselfget定义foodef
1条回答
网友
1楼 · 发布于 2024-04-26 11:09:36

您可以通过调用^{}构造函数来创建函数。但是请记住,此构造函数是未记录的,并且是特定于实现的。在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.

要创建代码对象,可以使用^{}

^{pr2}$

相关问题 更多 >