我有python类文件。
import re
regex = {
'a1': re.compile('(\d+)'),
}
# or A1_REGEX = re.compile('(\d+)')
class A1():
def toview(self, mystring):
data = regex['a1'].search(mystring)
if data:
......
OR
import re
class A1():
a1 = re.compile('(\d+)')
def toView(self, mystring):
data = a1.search(mystring)
if data:
.......
请有人告诉,哪一个更好,更准确。 ? 哪一个是python标准编码/ PEP8标准? 在这种情况下,是否有任何时间使用正则表达式的消耗或内存使用 可以考虑 ? 请在此添加您的意见或评论。 感谢您的宝贵意见。!
答案 0 :(得分:1)
第二种选择对我来说看起来更具可读性,因为这个类只是指自己,而不是指它周围的任何东西。就像Zen of Python:
一样可读性计数。
就性能而言,即使正则表达式的复杂性增加,也没有太大的区别。 regex module负责缓存模式,因此只编译一次:
传递给
re.match()
,re.search()
或re.compile()
的最新模式的编译版本被缓存,因此一次只使用几个正则表达式的程序不必担心编译正则表达式。
这样会更好:
import re
class A1():
def __init__(self):
self.preg = re.compile(r'(\d+)')
def toView(self, mystring):
data = self.preg.search(mystring)
if data:
pass
这样,继承就更清晰了:
class B1(A1):
def check(self, data):
return self.preg.match(data)