09 Python Decorators

无参装饰器

#1. decorator without arguments
def log_time_always(func):
    @wraps(func)
    def wrapped(*args, **kwargs):
        #1. get current time
        t1 = datetime.now()
        #2. run the function
        func(*args, **kwargs)
        #3. get current time
        t2 = datetime.now()
        print(f'in {func.__name__}, it took {t2-t1}')

    return wrapped

带参数的装饰器

#2. decorator with arguments, flag is True or False
def log_time(flag):
    def wrapper(func):
        @wraps(func)
        def wrapped(*args, **kwargs):
            # if flag is true, we need to log the time
            if flag:
                #1. get current time
                t1 = datetime.now()
                #2. run the function
                func(*args, **kwargs)
                #3. get current time
                t2 = datetime.now()
                print(f'in {func.__name__}, it took {t2-t1}')
            else:
                func(*args, **kwargs)
        return wrapped
    return wrapper

本质

  • 装饰器需要能够处理一个函数

无参

@decorator_1
def f():
  pass

等同于

def f():
  pass

f = decorator_1(f)

带参

@decorator_2('ok')
def f():
  pass

等同于

def f():
  pass

f = decorator_1('ok')(f)
……

Continue reading

08 Python Virtual Environment

Details

refer to offical document

Virtual environment

To create new virtual environment

usually in folder venv

python -m venv yourfoldername

enter virtual environment

source venv/bin/activate

exit virtual environment

deactivate

Pip usage

install package

pip install packagename

list installed packages

pip list

save installed packages to requirements.txt

pip freeze > requirements.txt

install packages from requirements.txt

pip install -r requirements.txt
……

Continue reading

07 Python 函数

函数

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# def func, snake case
# return value

# no args, no return
def add_two_number():
    print('a')

# 1 arg
def add_two_number_1(x):
    return x + 5 # return value

# return multiple value 
def two_number_2(x, y):
    c = x + y
    d = x - y
    return c, d

# args
def add_number(x, y, *args):
    print(f'x = {x}')
    print(f'y = {y}')
    print(f'args = {args} ')

# kwargs
# 
def add_number_1(x, y, *args, **kwargs):
    print(f'x = {x}')
    print(f'y = {y}') # f-string f'this is string, {x}'
    print(f'args = {args} ')
    print(f'kwargs = {kwargs} ')
# wrong
# def add_number_2(**kwargs, *args, x, y)
    # pass

# default
def add_number_3(x, y, c=10, d = True):
    print(c)

if __name__ == '__main__':
    # add_two_number()
    # print(add_two_number_1(6))
    # print(two_number_2(10, 5))
    # add_number(1,2, 3, 4, 5, 6)
    # add_number_1(1,2,3,4,5, total=5, ok=6)
    add_number_3(1,2, 20)

##高级用法

……

Continue reading

06 Python 控制,循环

条件控制

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

if __name__ == '__main__':
    a = 5
    if a > 0:
        print('a > 0')
    else:
        print('a < 0')

    if a > 0:
        pass
    elif a < 5:
        pass
    elif a < 10:
        pass
    else:
        pass

    if a > 0:
        if a < 5:
            print(a)
        else:
            print('a > 5')

循环控制

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

if __name__ == '__main__':
    # while condition
    a = 5
    while a > 0:
        # print(a)
        a = a -1
    # for in
    for i in range(10):
        print(i)

    # break the loop
    
    print('------------------')
    for i in range(10):
        print(i)
    else: # 
        print('done')
        
    # continue the loop
    print('------------------')
    for i in range(10):
        if i == 5:
            continue 
        print(i)
    count = 0
    while count < 5:
       print (count, " 小于 5")
       count = count + 1
    else:
       print (count, " 大于或等于 5")
……

Continue reading

Golang 导出 csv 乱码的问题

问题提出

golang最近导出csv的时候,如果用excel打开,会有乱码。在网上查到了解决方案,记录一下。

解决方案

  f, err := os.Create("data.csv")
	if err != nil {
		panic(err)
	}
	defer f.Close()

	f.WriteString("\xEF\xBB\xBF") // 写入UTF-8 BOM,避免使用Microsoft Excel打开乱码
  writer := csv.NewWriter(f)
	writer.Write([]string{"col 1", "col 2", "col 3"})
	writer.Flush() 
……

Continue reading

Golang 中通过gRPC调用Python实现的功能

背景

有时候,我们在python中实现了一个功能,这功能如果用golang重新写呢,会比较麻烦,如果要在golang中调用python中的功能。 方式有很多,主要就是两个程序如果沟通的问题,那方式就各种各样了,可以通过http协议,json/xml等格式,或者tcp, 当然还有个 选择就是gRPC

……

Continue reading

Class Object Method

对象中通过类或者实例的方法调用方式的不同

如果通过类中取得的方法,需要传入实例

class A(object):
    def test(self, *args):
        print(*args)

if __name__ == '__main__':
    a = A()
    a.test(7, 8, 9)
    # method from class object
    m1 = A.test
    m1(a, 7, 8, 9, 10)
    # method from instance object
    m2 = a.test
    m2(7, 8, 9, 10)

也就是说, 实例方法的第一个参数是实例本身,如果写decorator的时候,要特别注意

比如print_args这个decorator, 需要打印参数,就需要把第一个参数给选出来不作处理


def print_args(func):
    def wrapper(*args):
        _, *rest = args
        print("args: ", *rest)
        func(*args)
    return wrapper

class A(object):

    @print_args
    def test(self, *args):
        print(*args)

if __name__ == '__main__':
    a = A()
    a.test(7, 8, 9)
    # method from class object
    m1 = A.test
    m1(a, 7, 8, 9, 10)
    # method from instance object
    m2 = a.test
    m2(7, 8, 9, 10)
……

Continue reading