Advanced 04. Python global variables and functions

1. The global and local variables

By global keywords convert local variable to a global variable

num = 10


def demo1():
    print("demo1" + "-" * 50)

    # global 关键字,告诉 Python 解释器 num 是一个全局变量
    global num

    num = 100
    print(num)


def demo2():
    print("demo2" + "-" * 50)
    print(num)


# demo1() # 输出 100
demo2()  # 输出10

print("over")

2. Advanced Functions

  • A plurality of function return value
def measure():
    """返回当前的温度"""

    print("开始测量...")
    temp = 39
    wetness = 10
    print("测量结束...")

    return temp, wetness


temp, wetness = measure()

print(temp)
print(wetness)
  • Exchange two numbers
解法 1 —— 使用其他变量

    # 解法 1 - 使用临时变量
    c = b
    b = a
    a = c

解法 2 —— 不使用临时变量

    # 解法 2 - 不使用临时变量
    a = a + b
    b = a - b
    a = a - b

解法 3 —— 异或运算
	a = a ^ b
	b = a ^ b
	a = a ^ b
	
解法 4 —— Python 专有,利用元组

    a, b = b, a
  • Interview questions
def demo(num, num_list):

    print("函数内部代码")

    # num = num + num
    num += num
    # num_list.extend(num_list) 由于是调用方法,所以不会修改变量的引用
    # 函数执行结束后,外部数据同样会发生变化
    num_list += num_list   # 注意: Python中的列表+=是在原有集合上操作,要区别于scala

    print(num)
    print(num_list)
    print("函数代码完成")


gl_num = 9
gl_list = [1, 2, 3]
demo(gl_num, gl_list)
print(gl_num)
print(gl_list)
  • Multi-value parameter
    Sometimes the number of parameters may need to be able to handle a function is uncertain, at this time, you can use a multi-value parameter
    python, there are two multi-value parameter:
    * Before adding a parameter name can receive tuples
    Parameter name before adding two * can receive Dictionary
    Generally when a multi-value parameter named, accustomed to using the two names
    * args - store tuple parameters, preceded by a *
    ** kwargs - dictionary storage parameters, preceded by two *
    args is an abbreviation arguments, there is a variable meaning
    kw is the keyword abbreviations, kwargs can remember the key parameters
def demo(num, *args, **kwargs):
    print(num, type(num))
    print(args, type(args))
    print(kwargs, type(kwargs))


demo(1, 2, 3, 4, 5, name="小明", age=18, gender=True)

Here Insert Picture Description

  • Tuples and dictionaries unpacking
def demo(*args, **kwargs):

    print(args)
    print(kwargs)


# 需要将一个元组变量/字典变量传递给函数对应的参数
gl_nums = (1, 2, 3)
gl_xiaoming = {"name": "小明", "age": 18}

# 没有拆包,会把两个元素全部传给tuple, 而字典里面是空的
demo(gl_nums, gl_xiaoming)

# 进行了拆包,会把相应的元素传递给tuple和dict
demo(*gl_nums, **gl_xiaoming)

Here Insert Picture Description
Here Insert Picture Description

3. Python special function STR (Self) and __repr __ (self)

Published 85 original articles · won praise 12 · views 3757

Guess you like

Origin blog.csdn.net/fanjianhai/article/details/103551130