您可以使用函数属性。在Python中,函数是一级对象,因此您可以滥用此功能来模拟静态变量:
import re
def find_some_pattern(b):
if getattr(find_some_pattern, 'a', None) is None:
find_some_pattern.a = re.compile(r'^[A-Z]+\_(\d{1,2})$')
m = find_some_pattern.a.match(b)
if m is not None:
return m.groups()[0]
return 'NO MATCH'
现在,你可以试试:
try:
print(find_some_pattern.a)
except AttributeError:
print('No attribute a yet!')
for s in ('AAAA_1', 'aaa_1', 'BBBB_3', 'BB_333'):
print(find_some_pattern(s))
print(find_some_pattern.a)
这是输出:
No attribute a yet!
initialize a!
1
NO MATCH
3
NO MATCH
re.compile('^[A-Z]+\\_(\\d{1,2})$')
这不是最好的方法(包装器或可调用器更优雅,我建议你使用其中之一),但我认为这清楚地解释了以下含义:
在Python中,函数是一级对象。