简体   繁体   English

__init__类中的函数Dict |类 调用类时评估的函数

[英]Function in Class __init__ Dict | Functions Evaluated on Call of Class

I have a bunch of functions that I am storing in a dictionary used to gather data from a more "cryptic" source (I have written functions to access this data). 我将一堆函数存储在字典中,该字典用于从更“神秘”的源中收集数据(我编写了一些函数来访问此数据)。

In my code, I want to create "visibility" of what functions / parameters are loading variables used in the rest of the class. 在我的代码中,我想创建“可见性”,以了解哪些函数/参数正在加载该类其余部分中使用的变量。 So, I would like to have a class where, upon init, a dictionary of functions stands up that can be used by further functions in the class. 因此,我想拥有一个这样的类,在初始化时,会出现一个函数字典,该字典可被该类中的其他函数使用。 The issue I am running into is that I want these functions to be called only when they are retrieved from the dictionary by a later function. 我遇到的问题是,我希望仅在以后的函数从字典中检索这些函数时才调用它们。 I do not want the functions evaluated upon init . 我不希望在init上评估函数。

Problem: Some of the functions I am passing into the dictionary are "incomplete" as I would like to pass in additional parameters allowed via partial. 问题:我要传递到字典中的某些函数是“不完整的”,因为我想传递通过partial允许的其他参数。 The issue is that it appears init of the class evaluates all the functions in the dictionary rather than storing them as functions. 问题在于,类的init似乎会评估字典中的所有函数,而不是将其存储为函数。 I get an error from partial telling me that the first argument must be callable. 我从部分告诉我第一个参数必须是可调用的错误中得到了错误。

Here is an example of what I am doing (age works, month does not): 这是我在做什么的示例(年龄正常,月份无效):

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

SOLUTION

Ah, looks like the posted summary from 7stud works. 嗯,看起来像是7stud作品的发布摘要。 I just now just place the values / functions into the dict as partials with standard parameters and then pass additional ones as needed in the function call 我现在只是将值/函数作为带有标准参数的部分放入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

The issue is that it appears init of the class evaluates all the functions in the dictionary rather than storing them as functions. 问题在于,类的init似乎会评估字典中的所有函数,而不是将其存储为函数。

() is the function execution operator. ()是函数执行运算符。 So, when you write: 因此,当您编写:

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

the function lu.source is executed immediately, and the result is assigned to the "age" key in the dictionary. 函数lu.source立即执行,并将结果分配给字典中的"age"键。

Here's an example using partial : 这是使用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

Note that in the line: 请注意,在该行中:

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

the () is used with partial . ()partial So why does that work? 那为什么行得通呢? It works because partial returns a function-like thing, so you end up with something like this: 之所以有效,是因为partial 返回的是类似函数的东西,所以您最终得到这样的东西:

funcs["add_3"] = some_func

Here is sort of how partial works: 这是部分工作的方式:

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

Response to comment : 对评论的回应

Okay, you could do this: 好的,您可以这样做:

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

But that makes calling the function much more tortuous. 但这使调用该函数更加曲折。 If you are going to call the function with the arguments anyway, then why not imbed the arguments in the function using partial ? 如果仍然要使用参数调用函数,那么为什么不使用partial将参数嵌入函数中呢?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM