哪个是声明正则表达式模式的更好方法?

时间:2015-03-31 17:05:16

标签: python python-2.7 python-3.x scrapy pep8

我有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标准? 在这种情况下,是否有任何时间使用正则表达式的消耗或内存使用 可以考虑 ? 请在此添加您的意见或评论。 感谢您的宝贵意见。!

1 个答案:

答案 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)