我在字典中存储了一堆函数,用于从更“神秘”的源中收集数据(我编写了访问这些数据的函数)。你知道吗
在我的代码中,我想创建“可见性”,即加载类其余部分中使用的变量的函数/参数。所以,我想有一个类,在初始化时,一个函数字典可以被类中的其他函数使用。我遇到的问题是,我希望这些函数只有在以后的函数从字典中检索时才被调用。我不希望函数在init上求值。你知道吗
问题:我传递到字典中的一些函数是“不完整的”,因为我想通过partial传递允许的其他参数。问题是类的init对字典中的所有函数求值,而不是将它们存储为函数。partial告诉我第一个参数必须是可调用的,这是一个错误。你知道吗
下面是我正在做的一个例子(年龄起作用,月份不起作用):
from functools import partial as part
class A:
def __init__(self):
self.rawInput={
'age':lu.source('personalInfo', 'age', asArray=1)
,'month':lu.source('employInfo', 'months_employed')
}
self.outputDict={}
self.resultsDict={}
class output(object):
def age(self):
age = A().rawInput['age']
return len(age)
def month(self):
stuff=[]
for x in range(0,1):
month = part(A().rawInput['month'], x=x)
stuff.append(month)
return stuff
解决方案
啊,看起来像是7家工厂发布的总结。我现在只是将值/函数作为标准参数的部分放入dict中,然后在函数调用中根据需要传递其他值/函数
from functools import partial as part
def source(name, attrib, none=None):
if none!=None:
print 'ham'
else:
print 'eggs'
class A:
def __init__(self):
self.rawInput={
'age':part(source,'personalInfo', 'age')
,'month':part(source,'employInfo', 'months_employed')
}
self.outputDict={}
self.resultsDict={}
class output:
def age(self):
A().rawInput['age']()
def month(self):
x = 1
A().rawInput['month'](x)
c = A.output()
c.age()
c.month()
eggs
ham
()
是函数执行操作符。所以,当你写的时候:函数
lu.source
立即执行,结果被分配给字典中的"age"
键。你知道吗下面是一个使用
partial
的示例:请注意,行中:
()
与partial
一起使用。那为什么会这样呢?它之所以有效,是因为partial返回一个类似函数的东西,所以最终得到如下结果:以下是部分工作原理:
回复评论:
好吧,你可以这样做:
但这使得调用函数更加曲折。如果仍然要用参数调用函数,那么为什么不使用
partial
将参数嵌入函数中呢?你知道吗相关问题 更多 >
编程相关推荐