current position:Home>How IOS developers learn Python Programming 23 - Supplement 2

How IOS developers learn Python Programming 23 - Supplement 2

2022-02-01 15:41:34 Sissy's father

This is my participation 11 Yue Gengwen challenges 23 God , Check out the activity details :2021 The last time Gengwen challenge .

The singleton pattern

The singleton pattern : Is a common software design pattern . That is, the class contains only one instance .

Single instance mode can ensure that there is only one instance of a class in the system and that the instance is easy to be accessed by the outside world , Thus, it is convenient to control the number of instances and save system resources .
If you want to have only one object of a certain class in the system , Singleton is the best solution .

It is usually used in some resource managers , Such as logging .

Singleton mode implementation :

  • When the object does not exist , Create objects
  • When an object exists , Always return the currently created object
class single(object):
    __isinstance = None

    def __new__(cls, *args, **kwargs):
        if cls.__isinstance is None:
            cls.__isinstance = super().__new__(cls)
            return cls.__isinstance
            return cls.__isinstance

a = single()
b = single()
 Copy code 

Common built-in modules

sys modular

sys modular : be used for python Interpreter interaction .

sys Module common methods
  • sys.argv[]: A bridge to obtain parameters from outside the program  
    • sys.argv[0]: The file path of the program itself
    • sys.argv[1]: Parameters passed by external runtime
  • sys.verson: Used to display interpreter version information
  • sys.path: Used to display the module search path
  • sys.exit(): Used to exit the program

os modular

os Modules are operating system related modules .

os Module common methods
  • os.getcwd(): Used to print the current working directory
  • os.chdir(): Change the current working directory
  • os.makedirs(): Create multiple folders recursively
  • os.removedirs(): Delete multiple empty folders recursively
  • os.mkdir(): Create a single folder
  • os.rmdir(): Delete a single empty folder
  • os.path.exists(): Judge whether the file or folder under this path exists
  • os.path.join(): Splicing path

time modular

time Modules are time-dependent modules .

time Module common methods
  • time.sleep(): Delay execution time
  • time.time(): Second time stamp
  • time.localtime(): Local time
  • time.strftime(): Pass in the time tuple ,format Parameters determine the output time format
  • datetime It is also a time related module : 
    • Output current time

random modular

random modular : Random modules .

random Module common methods
  • random.random(): Used to generate a random number of characters in a specified range
  • random.randint(): Used to generate an integer in a specified range
  • random.choice(): Get a random element from the sequence
  • random.shuffle(): Used to scramble elements in a list
  • random.sample(): Randomly get a fragment of a specified length from a specified sequence
  • random.randrange(): From the specified range , Gets a random number in the set incremented by the specified cardinality

JSON modular

JSON Module common methods .

  • json.loads()json Turn to dictionary ( Applies to statements )
  • json.dumps(): The dictionary turns to json( Applies to statements )
  • json.load()json Turn to dictionary ( Applicable to documents )
  • json.dump(): The dictionary turns to json( Applicable to documents )

Recursive function

The function directly or indirectly calls the function itself , This function is called a recursive function .

for example , Calculate the factorial :

  • Factorial essence :n! = 1 * 2 * 3 * ... * n;
  • Use functions func(n) Express , It can be seen that : 
    • func(n) = n! = 1 * 2 * 3 * ... * (n-1) * n = (n-1)! * n = func(n-1) * n.

therefore ,func(n) It can be expressed as n * func(n-1)

def get_nums(num):
    return num * get_nums(num-1)
# 3*5*4*3*2*1*f(0)
res = get_nums(6)
 Copy code 

️ Be careful : If you directly use the above code , The running result will find that the recursive function itself has no end condition , So we need to set our own end conditions , Terminate the call to the function .

def get_nums(num):
    if num > 1:
        return num * get_nums(num-1)
        return 1
# 6*5*4*3*2*1*f(0)
res = get_nums(6)
 Copy code 

copyright notice
author[Sissy's father],Please bring the original link to reprint, thank you.

Random recommended