如何用Python函数模拟Cstyle函数指针

2024-06-06 09:45:49 发布

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

假设我有一个硬编码的函数,当在较大的字符串中找到子字符串的实例时,该函数使子字符串变为小写,例如:

def process_record(header, needle, pattern):
    sequence = needle
    for idx in [m.start() for m in re.finditer(pattern, needle)]:
        offset = idx + len(pattern)
        sequence = sequence[:idx] + needle[idx:offset].lower() + sequence[offset:]
    sys.stdout.write('%s\n%s\n' % (header, sequence))

这样做很好,例如:

>>> process_record('>foo', 'ABCDEF', 'BCD')
>foo
AbcdEF

我想做的是将其泛化,将字符串函数(lower,在本例中,它可以是任何基元类型或类的函数)作为参数传入。比如:

def process_record(header, needle, pattern, fn):
    sequence = needle
    for idx in [m.start() for m in re.finditer(pattern, needle)]:
        offset = idx + len(pattern)
        sequence = sequence[:idx] + needle[idx:offset].fn() + sequence[offset:]
    sys.stdout.write('%s\n%s\n' % (header, sequence))

这不起作用(这就是为什么我要问这个问题),但希望这能证明这个想法,以一种可读的方式来概括函数的作用。你知道吗

我想有一个选择是编写一个helper函数来包装stringInstance.lower()并传递字符串的副本,这既低效又笨拙。我希望有一种Python专家知道的更优雅的方法。你知道吗

例如,使用C时,我会将指向要作为参数运行的函数的指针传递给process_record(),并直接在感兴趣的变量上运行函数指针。你知道吗

在Python中使用字符串基元函数(或基元或其他类上的类似函数)时,执行相同操作的语法是什么?你知道吗


Tags: 函数字符串infordefrecordprocesslower
2条回答

你的例子有点复杂,所以我要把它分成两个不同的问题:

1)如何提供函数作为参数?你知道吗

函数是与其他对象一样的对象,可以按预期传递,例如:

 def apply(val, func):
    # e.g. ("X", string.lower) -> "x"
    #      ("X", lambda x: x * 2) -> "XX"
     return func(val)

在你的例子中,你可以这样做

def process_record(..., func):
    ...
       sequence = ... func(needle[idx:offset]) ...
    ...

我不推荐的另一种方法是

def apply_by_name(val, method_name):
    # e.g. ("X", "lower") -> "x"
    return getattr(val, method_name)()

2)如何对字符串中正则表达式的每个匹配应用效果?你知道吗

为此,我建议使用内置的“sub”函数,它既接受字符串,也接受函数。你知道吗

>>> re.sub('[aeiou]', '!', 'the quick brown fox')
'th! q!!ck br!wn f!x'

def foo(match):
   v = match.group()
   if v == 'i': return '!!!!!!!'
   elif v in 'eo': return v * 2
   else: return v.upper()

>>> re.sub('[aeiou]', foo, 'the quick brown fox')
'thee qU!!!!!!!ck broown foox'

希望这有帮助!你知道吗

一般来说,使用这种方法:

def call_fn(arg, fn):
    return fn(arg)

call_fn('FOO', str.lower) # 'foo'

Python中方法的定义总是以self作为第一个参数。通过将方法作为的属性调用,可以强制该参数的值。你知道吗

相关问题 更多 >