Download Python Classes, Modules, Time Functions, and Regular Expressions and more Study notes Computer Science in PDF only on Docsity! Introduction to Python [3]
Introduction to Networks
and their Applications
22C:118, Fall 2005
Alessio Signorini <alessio-signorini@ uiowa.edu>
Class Objects Create a new class in Python is simple. Just write class MyClass (class1, class2, ...): “This is what this class does, nothing for now!” do something Special methods of each class are __init__(self) # when istance is created __del__(self) # when istance is deleted __getattribute__(self, name) # when attrib is requested __doc__ # documentation string Importing modules Modules are imported at the beginning of a program with from sys import argv or from sys import * # import all attributes of sys To use an imported attributes just write something like print sys.argv[0] # print the command launched or for argument in sys.argv print argument # print list of all the arguments Time functions If in your programs you need to work with the time, import the module time and then use the following functions: time() # float representing UTC time since EPOCH asctime() # return a string with the current time localtime() # return a tuple with (y,m,d,h,mm,ss,wd,jd,l) strftime() # return a formatted string with current time sleep(x) # sleep for x seconds For a more sophisticated time management you should consider to use the module MxDateTime. Regular Expressions Regular expressions are powerful tools that allows to scan trough strings identifying interesting parts or replacing characters. In Python regular expressions are supported thanks to the module re. (add import re at the beginning of your code) To use the module, you have to create a regular expression object with your settings for the search: reo = re.compile(r'\w+') Regular Expressions Examples r/'aa.*bb' # matches “aabb” as “aaabb” or “aacbbc” r/'aa.+bb' # matches “aa23bb” or “aacbb” but not “aabb” r/'\bhis\b' # matches “his” but not “this” or “history” r/'\bher\w+' # matches “her” or “herbal” but not “mother” r/'\d+' # matches “123” and “aa23bb” r/'\b\d{6,6}\b' # matches only numbers of six digits r/'\d\d' # matches two following digits as in or “123” r/'\d\d\w\w\w' # matches 2 digits followed by 3 chars (12jan) Regular Expressions Examples import re r1 = re.compile(r'box') if r1.match(“inbox”): print “Match succeded!” else: print “Match failed!” # prints: match failed if r1.search(“inbox)”: print “Search succeded!” # prints: search succeded else: print “Search failed!”