OOP basics & OOP advanced & RE modules | Cloud computing

1. Write game characters

1.1 problems

To create a program, the requirements are as follows:

  1. Create a game character class
  2. Game characters have names, weapons and other attributes
  3. Game characters have methods to attack and walk
  4. Weapons are realized through weapons

1.2 scheme

Because the game characters and weapons are implemented by classes, and the two classes are completely different, they can be implemented by combination. Take an instance of the weapon class as an attribute of the game character.

1.3 steps

To implement this case, you need to follow the following steps.

Step 1: Script

[root@localhost day07]# vim game_role.py
class Weapon:
    def __init__(self, wname, strength):
        self.wname = wname
        self.strength = strength
class Warrior:
    def __init__(self, name, weapon):
        self.name = name
        self.weapon = weapon
    def speak(self, words):
        print("I'm %s, %s" % (self.name, words))
    def show_me(self):
        print("I am%s, I am a soldier. My weapon is%s" % (self.name, self.weapon.wname))
if __name__ == '__main__':
    blade = Weapon('falchion', 100)
    print(blade.wname, blade.strength)
    gy = Warrior('Guan Yu', blade)
    gy.show_me()
    cz = Weapon('Buddhist monk 's stick', 100)
    lzs = Warrior('lu zhishen', cz)
    lzs.show_me()

Step 2: test script execution

[root@localhost day07]# python3  game_role.py
 Qinglong Yanyue Sabre 100
 I'm Guan Yu, I am a soldier. The weapon I use is Qinglong Yanyue Dao
 I'm Lu Zhishen, I am a soldier. My weapon is a Zen stick

2. Publisher procedures

2.1 problems

Create books Py file to achieve the following objectives:

  1. Write a Book class for publishers
  2. The Book class has attributes such as Book name, author, and number of pages
  3. When printing an instance, the title of the book is output
  4. When the instance is called, the author of the book is displayed

2.2 scheme

Create a class in which three magic methods are created:

  1. __ init__ Method:__ init__ Method is used to initialize the instance property. It will be called automatically after the object is created__ init__ Method, which belongs to the constructor method. The book name and author properties are initialized here

  2. __ str__ Method: after creating the object, print the instance object pybook, return the book name, and print the book name

  3. __ call__ Method: after creating an object, you can call the method like calling a function, simulate the behavior of the function, and print the book name and author

2.3 steps

To implement this case, you need to follow the following steps.

Step 1: Script

[root@localhost day07] # vim books.py
#!/usr/bin/env python3
class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author
    def __str__(self):
        return '<Book: %s>' % self.title
    def __call__(self):
        print('<%s> is written by %s.' % (self.title, self.author))
if __name__ == '__main__':
    pybook = Book('Core Python', 'Weysley')
    print(pybook)  # Call__ str__
    pybook()   # Call__ call__

Step 2: test script execution

[root@localhost day07]# python3 books.py 
<Book: Core Python>
<Core Python> is written by Weysley.

3. Analyze apache access logs

3.1 problems

Write count_patt.py script to implement an Apache log analysis script:

  1. Count the number of times each client accesses the apache server
  2. The statistical information is displayed in the form of a dictionary
  3. Count the access times of Firefox and MSIE clients respectively
  4. It is realized by functional programming and object-oriented programming respectively

3.2 scheme

collections is a collection module built in python. Many useful collection classes are provided in the module. The counter class is a simple counter, which is stored in the form of dictionary key value pairs, in which the searched elements are used as keys and the number of occurrences is used as values

Implementation process:

  1. Instantiate a counter

  2. Instantiate regular expression

  3. Open the file as an object

  4. Find each line of the file through a regular expression

  5. If the result is found

  6. Add the result to the counter and update the original data through the update method

  7. Return counter

  8. Pass the file address and regular expression as arguments to the function

3.3 steps

To implement this case, you need to follow the following steps.

Step 1: Script

[root@localhost day08]# vim count_patt.py
#!/usr/bin/env python3
import re
import collections
#fname file address patt regular expression
def count_patt(fname,patt):
    
    counter = collections.Counter()
   
    cpatt = re.compile(patt)
        with open(fname) as fobj:
        for line in fobj:
           
            m = cpatt.search(line)
           
            if m:
              
                counter.update([m.group()])
  
    return counter
if __name__ == "__main__":
    fname = "access_log.txt"
    ip_patt = "^(\d+\.){3}\d+"
    a = count_patt(fname,ip_patt)
    print(a)
    br_patt = "Firefox|MSIE|Chrome"
    b = count_patt(fname,br_patt)
    print(b)

This case can also be implemented in an object-oriented manner:

Implementation process:

  1. Create class CountPatt

  2. Defining construction methods to create regular objects

  3. Define class methods

  4. Create counter object

  5. open the text file

  6. Find each line of the file through a regular expression

  7. If the result is found

  8. Add the result to the counter and update the original data through the update method

  9. Return counter

  10. Pass the file address and regular expression as arguments to the function

[root@localhost day08]# vim count_patt2.py
#!/usr/bin/env python3
import re
import collections
import re
import collections
class CountPatt:
    
    def __init__(self,patt):
        self.cpatt = re.compile(patt)
    
    def count_patt(self,fname):
        
        counter = collections.Counter()
       
        with open(fname) as fobj:
       
            for line in fobj:
       
                m = self.cpatt.search(line)
        
                if m:
        
                    counter.update([m.group()])
    
        return counter
if __name__ == "__main__":
    fname = "access_log.txt"
    ip_patt = "^(\d+\.){3}\d+"
    br_patt = "Firefox|MSIE|Chrome"
    ip = CountPatt(ip_patt)
    print(ip.count_patt(fname))
    br = CountPatt(br_patt)
    print(br.count_patt(fname))

Step 2: test script execution

[root@localhost day08]# python3 count_patt.py 
Counter({'172.40.0.54': 391,'172.40.50.116': 244,'201.1.1.254': 173,'127.0.0.1': 121,'201.1.2.254': 119})
Counter({'Firefox': 870,'MSIE': 391,'Chrome': 24})
[root@localhost day08]# python3 count_patt2.py 
Counter({'172.40.0.54': 391,'172.40.50.116': 244,'201.1.1.254': 173,'127.0.0.1': 121,'201.1.2.254': 119})
Counter({'Firefox': 870,'MSIE': 391,'Chrome': 24})

Exercise

1 what are the commonly used magic methods in OOP programming?

  • init: the method that will be called by default when instantiating a class instance
  • str: method called when printing / displaying instances
  • call: used to create callable instances

2 when to use combination and derivation in OOP programming?

  • Composition works well when there are significant differences between classes and the smaller class is the component required by the larger class
  • However, when designing "the same class but with some different functions", derivation is used

3 how to match strings that are all numbers with regular expressions?

  • '^\d+$'
  • '^[0-9]+$'

4 re.match and re What is the difference between search?

  • re.match can only match from the beginning of a string
  • re.search can match anywhere in the string

5. What method can be used to extract the content matched by the following regular expressions?

m = re.search('f..', 'seafood')
m.group()

6 how to match all qualified substrings in a string through regular expressions.

  • re.findall method
  • re. Finder method

7 re. What is the function of compile?

  • Compile the regular expression pattern and return a regular expression object
  • In the case of a large number of matches, the efficiency can be improved

In case of infringement, please contact the author to delete

Keywords: Python Operation & Maintenance shell OOP cloud computing

Added by germanjulian on Sun, 02 Jan 2022 20:02:50 +0200