字典中的函数按值传递
Function pass-by-value from dictionary
我正在尝试编写一个程序来检查字典中的操作并调用匹配 'key' 的函数。
此程序将根据 'key' 的内容解析该行。
我的问题是,如何将字符串传递给字典调用的函数,以便函数可以解析它,因为字符串并不总是相同,字符串的解析方式也不同。
def format1(opline): # r-type: rd, rs, rt
opline = opline.split('', 1)[1] # removes instruction
rd, rs, rt = opline.split() # splits into 3 registers
return rd, rs, rt # returns all registers
inst_match = {'add' : format1} # dictionary (more.
# key/funct pairs
# will be added
instruction_storage = 'add 9 0 255'
instructions = instruction_storage.split()[0] # get key from string
inst_match[instructions](instruction_storage) # passes key to search and string to pass into function
^ 上面的代码只是一个测试。我最终将从多行文件中读取 "instruction_storage"。
我不太清楚你到底在找什么,但我猜一下:
def format1(opline, string):
print('format1({!r}, {!r})'.format(opline, string))
opline = opline.split(' ', 1)[1]
rd, rs, rt = opline.split()
return rd, rs, rt
def format2(opline, string):
print('format2({!r}, {!r})'.format(opline, string))
opline = opline.split(' ', 1)[1]
rd, rs, rt = opline.split()
return rd, rs, rt
inst_match = {'add': format1,
'sub': format2}
instruction_storage = [('add 9 0 255', 'string1'),
('sub 10 1 127', 'string2')]
for instruction in instruction_storage:
opline, string = instruction
opcode = opline.split()[0]
try:
inst_match[opcode](opline, string)
except KeyError:
print('unknown instruction: {!r}'.format(opcode))
输出:
format1('add 9 0 255', 'string1')
format2('sub 10 1 127', 'string2')
我正在尝试编写一个程序来检查字典中的操作并调用匹配 'key' 的函数。
此程序将根据 'key' 的内容解析该行。
我的问题是,如何将字符串传递给字典调用的函数,以便函数可以解析它,因为字符串并不总是相同,字符串的解析方式也不同。
def format1(opline): # r-type: rd, rs, rt
opline = opline.split('', 1)[1] # removes instruction
rd, rs, rt = opline.split() # splits into 3 registers
return rd, rs, rt # returns all registers
inst_match = {'add' : format1} # dictionary (more.
# key/funct pairs
# will be added
instruction_storage = 'add 9 0 255'
instructions = instruction_storage.split()[0] # get key from string
inst_match[instructions](instruction_storage) # passes key to search and string to pass into function
^ 上面的代码只是一个测试。我最终将从多行文件中读取 "instruction_storage"。
我不太清楚你到底在找什么,但我猜一下:
def format1(opline, string):
print('format1({!r}, {!r})'.format(opline, string))
opline = opline.split(' ', 1)[1]
rd, rs, rt = opline.split()
return rd, rs, rt
def format2(opline, string):
print('format2({!r}, {!r})'.format(opline, string))
opline = opline.split(' ', 1)[1]
rd, rs, rt = opline.split()
return rd, rs, rt
inst_match = {'add': format1,
'sub': format2}
instruction_storage = [('add 9 0 255', 'string1'),
('sub 10 1 127', 'string2')]
for instruction in instruction_storage:
opline, string = instruction
opcode = opline.split()[0]
try:
inst_match[opcode](opline, string)
except KeyError:
print('unknown instruction: {!r}'.format(opcode))
输出:
format1('add 9 0 255', 'string1')
format2('sub 10 1 127', 'string2')