如何将方法用作词典中的项?Python 2.x版

2024-06-16 08:31:27 发布

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

我只想在获取for中的项时使用该方法。 但是,当cicle启动时,所有方法都被调用。 我试过使用dict[key](函数参数),但我不知道参数 在cicle的最后一部分


class Func():
    def LD(self,r,r2):
        self.reg[str(r)]=self.reg[str(r2)]    
        self.cic[0]=self.cic[0]+4
        self.cic[1]=self.cic[1]+1
        self.cic[2]=self.cic[2]+1
        print 'LD '+str(r)+','+str(r2)

class Data(Func):
    reg={'A':0,'B':0,'C':12,'D':0,'E':0,'H':0,'L':0,'F':0,'IX':0,'IY':0}
    cic=[0,0,0]

Dat=Data()


LI={'C':Dat.LD('A','B'),'D':Dat.LD('A','C')}
LD={'A':Dat.LD('D','E'),'B':Dat.LD('D','F')}
L={'1':LD,'2':LI}

Cod=['1A','2D']
cont=0
for temp in L:                                                           
    if Cod[0] in temp:                                                   
        if Cod[1] in temp[cod[0]]:                                    
            temp[cod[0]].get(cod[1])


Tags: 方法inselfforregtempclassdat
1条回答
网友
1楼 · 发布于 2024-06-16 08:31:27

你的问题是,你不是一开始就把方法放到字典里,而是调用方法,把结果放到字典里。例如:

LI={'C':Dat.LD('A','B'),'D':Dat.LD('A','C')}

这将立即调用Dat.LD('A', 'B'),并使其成为'C'键的值

这正是^{}函数的作用。正如医生所说:

The partial() is used for partial function application which “freezes” some portion of a function’s arguments and/or keywords resulting in a new object with a simplified signature. For example, partial() can be used to create a callable that behaves like the int() function where the base argument defaults to two:

>>> from functools import partial
>>> basetwo = partial(int, base=2)
>>> basetwo.__doc__ = 'Convert base 2 string to an int.'
>>> basetwo('10010')
18

因此,对于您的问题,您需要一个行为类似于Dat.LD方法的新对象,但其中的参数已经“冻结”为'A', 'B'

from functools import partial

LI={'C': partial(Dat.LD, 'A', 'B'),
    'D': partial(Dat.LD, 'A', 'C')}

或者,您也可以使用deflambda显式创建一个新函数来包装方法调用:

LI={'C': lambda: Dat.LD('A', 'B'),
    'D': lambda: Dat.LD('A', 'C')}

相关问题 更多 >