Class __init__ 字典中的函数 |在调用 Class 时评估的函数

Function in Class __init__ Dict | Functions Evaluated on Call of Class

我有一堆函数存储在字典中,用于从更多 "cryptic" 来源收集数据(我已经编写了函数来访问这些数据)。

在我的代码中,我想创建 "visibility" 哪些函数/参数正在加载其余 class 中使用的变量。因此,我想要一个 class,其中在初始化时会建立一个函数字典,供 class 中的其他函数使用。我 运行 遇到的问题是,我希望这些函数仅在它们被稍后的函数从字典中检索时才被调用。我不希望在 init.

上评估函数

问题:我传递给字典的一些函数是 "incomplete",因为我想传递部分允许的附加参数。问题是 class 的 init 会评估字典中的所有函数,而不是将它们存储为函数。我收到部分错误消息,告诉我第一个参数必须是可调用的。

这是我正在做的一个例子(年龄有效,月份无效):

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

解决方案

啊,好像是7stud作品的贴子总结。我现在只是将值/函数作为带有标准参数的部分放入字典中,然后根据需要在函数调用中传递额外的参数

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

The issue is that it appears init of the class evaluates all the functions in the dictionary rather than storing them as functions.

()是函数执行运算符。所以,当你写:

'age':lu.source('personalInfo', 'age', asArray=1) 

函数lu.source立即执行,结果赋值给字典中的"age"

这是一个使用 partial 的例子:

from functools import partial

def myadd(x, y):
    return x+y

def mysubtract(x, y):
    return x-y


funcs = {}

funcs["add_3"] = partial(myadd, 3)
funcs["subtr_from_10"] = partial(mysubtract, 10)


print(
    funcs["add_3"](2)  #Note the function execution operator
)

print(
    funcs["subtr_from_10"](3)  #Note the function execution operator
)

--output:--
5
7

注意在行中:

funcs["add_3"] = partial(myadd, 3)

()partial 一起使用。那为什么会这样呢?它之所以有效,是因为 partial returns 是一个类似函数的东西,所以你最终会得到这样的东西:

funcs["add_3"] = some_func

部分工作原理如下:

def mypartial(func, x):

    def newfunc(val):
        return x + val

    return newfunc

add_3 = mypartial(myadd, 3)  #equivalent to add_3 = newfunc
print(add_3(2))  #=>5

回复评论:

好的,你可以这样做:

def myadd(x, y, z):
    return x+y+z

funcs = {}

funcs["add"] = {
    "func": myadd,
    "args": (3, 4)
}


func = funcs["add"]["func"]
args = funcs["add"]["args"]
result = func(*args, z=2)

print(result)  #=> 9

但这使得调用函数变得更加曲折。如果无论如何都要使用参数调用函数,那么为什么不使用 partial?

将参数嵌入函数中呢?