5 Python tips per day (day1)

5 Python tips per day - day1

1. assert

(1) Usage

assert expression, 'message'

When the expression statement is not satisfied, an assertion error will be raise d to ensure that the code after the assert statement meets the expression.

(2) Apply

Tell the programmer that an unrecoverable error has occurred. It is used for the internal self-test of the program to explain the impossible error in the program.

Used for simple custom exception error warnings.

(3) Attention

· cannot be used for inspection data

Using the - o and - oo identifiers on the command line disables assertions globally.

(4) Examples

def AssertTest(num_):
    assert num_ > 10, 'num is less than 10'

if __name__ == '__main__':
    num = int(input("input num: "))

When 3 is entered, the program will report an error:

AssertionError: num is less than 10
2. Context management: with statements are supported in custom classes

(1) Add to custom objects__ enter and__ exit__ method. When the execution process enters the with statement context, Python calls__ enter to obtain resources; When you leave the with context, Python calls__ exit__ Free resources

(2) Examples

class withClass:

    def __init__(self):
        self.resource = 0

    def __enter__(self):
        self.resource += 1
        print(f'Get resources resource: {self.resource}')

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.resource = 0
        print(f"Release resources resource: {self.resource}")

if __name__ == '__main__':
    with withClass() as test:


Get resources resource: 1
 Release resources resource: 0

(3) Apply

Reading and writing of documents; Data cleaning or preprocessing; The automatic acquisition and release of resources are related to avoid the occupation of resources (such as the connection of data files and databases).

3. Context management: @contextlib.contextmanager

(1) Use the @ contextlib.contextmanager decorator to define a generator based factory function for resources, which will automatically support the with statement.

(2)Cite an example

# For an application scenario, add a book name before and after a book name
def book_mark():
    print('<', end='')
    yield  # The result does not have to be returned after yield, which is purely an interrupt
    print('>', end='')

if __name__ == '__main__':
    # Derivative usage: add a piece of code before and after the code to be executed
    # Especially for the source code of some frameworks, we can't modify it directly in the source code
    # The second is the pursuit of encapsulation and reusability
    with book_mark():
        print("And drink up life", end='')
[out] <And drink up life
4. Single underline

(1) Pre single underline

It has no effect on the program itself, just a hint - the Python community has agreed that single underlined variables or methods can only be used inside the class.

(2) Post single underline

It is used to avoid the conflict between the naming of variables and Python built-in keywords. For example, the tag used to find < div class = "container" >... < / div > in bs4 uses the parameter class_='container'; And naming conflicts with built-in keywords.

I usually use a single underscore to identify the variable names in the function that will be the same as the main function.

5. Double underline

(1) Pre underline

The leading double underscore allows the Python interpreter to override the attribute name to avoid naming conflicts in subclasses. This is also called name rewriting, that is, the interpreter changes the name of the variable.

a. examples

_MyClass__myname = "myClass"

class MyClass:

    def getMyname(self):

if __name__ == '__main__':
[out] myClass

This example shows that_ MyClass__myname = "myClass" is a global variable, and then access the variable in the class environment of MyClass. Because of name rewriting, the getMyname () method in the class only uses__ myname can reference_ MyClass__myname global variable.

b. Double underscores can also indicate private properties for classes

class MyClass:

    def __init__(self):
        self.__data = 1234

if __name__ == '__main__':
    mc = MyClass()
[out] AttributeError: 'MyClass' object has no attribute '__data'

However, using this method to indicate that private attributes also have risks, and data can also be accessed through the following methods

mc = MyClass()
[out] 1234

c. Double underline before and after

Some methods with double underlined names represent some special methods in the class, which will be revealed later. It should be noted that when customizing variable names or function names, try to avoid using double underscores before and after.

Tags: Python

Posted on Sun, 24 Oct 2021 02:22:38 -0400 by friday_13