Summary of python function and object-oriented programming

Summary of function and object-oriented programming

This week I mainly studied function and object-oriented programming. The following is a summary and supplement to function and object-oriented programming.

Function part

How to write a function

# Function template with known parameters
def Function name(parameter): 
    ...
    return ...
    
# Unable to determine number of parameters function template
def Function name(*args):
    # Variable parameters can be placed in a for loop to get the value of each parameter
    for arg in args:
        ...
    return ...

# Unable to determine whether to specify parameter name
def Function name(*args, **kwargs):
    for arg in args: # This step is performed when no parameter name is passed in
        ...
    for value in kwargs.values():# This step is performed when the parameter name is passed in
        ... 
    return ...
 

When defining a function, the parameters written in front of * are position parameters, which only need to be seated according to the number
The parameters written after * are named keyword parameters and must be written as "parameter name = parameter value"

Global and local variables of function

Global variable: a variable that is not written in any function
Local variable: a variable defined inside a function
Searching for a variable in a Python program is performed in LEGB order

Local scope - > nested scope - > global scope - > built in scope
Global: declare to use a global variable or define a local variable to put it into the global scope
nonlocal: declare variables that use nested scopes (no local variables)

Example: CRAPS gambling game
The player shakes two dice. If 7 or 11 points are shaken for the first time, the player wins; If you shake out 2 points, 3 points and 12 points, the dealer wins;
If you shake out other points, the game continues and the player shakes the dice again; If the player shakes the points for the first time, the player wins;
If the player shakes out 7 points, the dealer wins; If the player shakes out other points, the game continues, and the player shakes the dice again until the winner is determined.

Before the game starts, the player has an initial fund of 1000 yuan. The player can bet. If he wins, he will get the bet amount, and if he loses, he will deduct the bet amount,
The condition for the end of the game is that the player loses all his money

import random

m = 1000


def roll_dice(num):
    """
    Chromophore
    
    :param num: Number of dice
    :return: Shake out points
    """
    q = 0
    for _ in range(num):
        q += random.randrange(1, 7)
    return q


def win():
    """
    win
    """
    global m
    m += x
    print('Player wins')

def lose():
    """
    transport
    """
    global m
    m -= x
    print('Zhuang Jiasheng')


# x = int(input('input bet amount: ')
while m > 0:
    print(f'Players' existing funds:{m}')
    x = 0
    while x <= 0 or x > m:
        try:
            x = int(input('Enter the bet amount:'))
        except ValueError:
            pass
    s1 = roll_dice(2)
    print(f'Points shaken for the first time:{s1}')
    if s1 in (7, 11):
        win()
    elif s1 in (2, 3, 12):
        lose()
    else:
        while True:
            s2 = roll_dice(2)
            print(f'The game continues, and the player shakes out the points:{s2}')
            if s2 == s1:
                win()
                break
            elif s2 == 7:
                lose()
                break
print('The player goes bankrupt and the game is over')

Example 2 write a function to judge whether a positive integer is a "happy number".
For a positive integer, replace the number with the sum of squares of the numbers at each position, and then repeat the process,
If the number becomes 1, this number is a happy number. If the infinite cycle does not change to 1, this number is not a happy number.

def is_happhy_num(num):
    """
    Judge whether a positive integer is a happy number
    :param num:Enter a positive integer
    :return:Happy number return True,Otherwise return False
    """
    list1 = []
    while True:
        x = 0
        while num > 0:
            x += (num % 10) ** 2
            num = num // 10

        num = x
        if num not in list1:
            list1.append(num)
        else:
            return False

        if x == 1:
            return True
if __name__ == '__main__':
    x = int(input('Enter a positive integer:'))

    if is_happhy_num(x):
        print(f'{x}It's a happy number')
    else:
        print(f'{x}Not happy number')

Object oriented programming

Four pillars of object-oriented programming

Abstraction: extracting commonalities
Encapsulation: logically assemble data and functions that manipulate data into a whole
Inheritance: extend an existing class to create a new class
Polymorphism: send the same message to different objects, and different objects perform different behaviors

Magic Methods

Magic method: a method with special purpose and meaning
__ init__: Initialization method
__ str__: Gets the string representation of the object
__ repr__: Gets the string representation of the object, puts the object in the container, and calls the print output.
__ lt__: Compare sizes

Dynamic attributes and static methods

Dynamic properties

A language whose structure can be changed at runtime. For example, new functions, objects, or even code can be introduced, existing functions can be deleted, or other structural changes can be made.
In Python, we can dynamically add attributes to objects

Static method

The functions written in classes are usually called methods. They are basically messages sent to objects
But sometimes, our message is not sent to the object, but to the class. At this time, we will use static methods.

Object method, class method and static method can all be defined by class name The difference is whether the first parameter of the method is an ordinary object, a class object, or an object that does not accept messages

In the object-oriented world, everything is an object, and the class we define is also an object, so the class can also receive messages, and the corresponding method is class method or static method. Through inheritance, we can create new classes from existing classes and reuse the existing class code.

Keywords: Python

Added by php_gromnie on Tue, 28 Dec 2021 01:41:52 +0200