-1

I have python class file.

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:
            .......

Please anyone tell, which one is better and more accurate. ? Which one is python standard coding/PEP8 standard ? In this case, is there any time consumptions or memory usage for regex usage can be considered ? Please add your opinions or comments to this. Thanks for your valuable comments .!

Finwood
  • 3,829
  • 1
  • 19
  • 36
  • mind that in your class methods the first argument always is a reference to the class instance, often called `self` – Finwood Mar 31 '15 at 17:49

1 Answers1

1

The second alternative looks much more readable to me, since the class is only referring to itself, not to anything around it. Like in the Zen of Python:

Readability counts.

As for performance, there will be no great difference, even if the regular expression increases in complexity. The regex module takes care of caching patterns, so it will be compiled only once:

The compiled versions of the most recent patterns passed to re.match(), re.search() or re.compile() are cached, so programs that use only a few regular expressions at a time needn’t worry about compiling regular expressions.


edit

This would be still nicer:

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

This way, inheritance is much cleaner:

class B1(A1):
    def check(self, data):
        return self.preg.match(data)
Community
  • 1
  • 1
Finwood
  • 3,829
  • 1
  • 19
  • 36