python中什么是通用的方法,它们是如何生成的?

2024-10-06 11:27:43 发布

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

Apologies upfront if this is a dupe; I search for "_curried python" and got 14 results, and then simply _curried" and that only bumped up to 33 results, and none seemed to help out...

问题:今天我在我们的代码库中遇到了一个我最初认为是错误的地方,这是嫌疑犯:

student.recalculate_gpa()

现在,我怀疑这是一个打字错误,因为student是一个没有recalculate_gpa方法的Student类的实例。但是,它有一个calculate_gpa方法:

^{pr2}$

(其中User是标准的django用户类)但是,代码没有出错,这对我来说毫无意义。所以我检查了一下,发现了这个:

... (a bunch of methods)
('calculate_gpa', <unbound method Student.calculate_gpa>),
... (some more methods)
('recalculate_gpa', <unbound method Student._curried>),

奇怪的是,recalculate_gpa实际上是一种方法。但它究竟从何而来?我在我们的代码库中搜索“_curried”,但什么也没找到,所以这一定是一些Django相关的行为。当然,我希望在我们的项目中的某个地方,我们已经描述了动态命名函数是如何形成的,因为recalculate似乎是calculate的一个看似合理的派生词,但是我真的不知道从哪里开始寻找。在

因此,我的问题是:如何生成像上面这样的curry方法,我应该从哪里开始寻找我们自己的代码库是如何curry的?在

先谢谢你!在


Tags: andto方法代码地方错误studentresults
1条回答
网友
1楼 · 发布于 2024-10-06 11:27:43

curried方法是在实际调用方法之前部分调用它

例如

from functools import partial
from itertools import count
def my_pow(x,y):
    return x**y

curried_pow2n = partial(my_pow,x=2)

for i in count(0): #print the 2**i
    print curried_pow2n(i)

您还可以使用lambda轻松实现它

^{pr2}$

虽然我不确定这是否与您的实际问题有关。。。在

django还提供了一个非常类似于functools.partial在

^{3}$

(来自https://stackoverflow.com/a/25915489/541038

所以您可能需要查找Student.recalculate_gpa =

或者在Student.__init__方法中为self.recalculate_gpa =

你可能不会发现它在寻找def recalculate_gpa

相关问题 更多 >