Python中的参数传递

基本参数

def hello(greeting, name):
    print('{0}, {1}!'.format(greeting, name))

hello("Hello", "World")

默认参数

def hello2(name="World", greeting="Hello"):
  print('{0}, {1}!'.format(greeting, name))

hello2() # Hello, World!
hello2("Noah") # Hello, Noah!
hello2(name="Noah") # Hello, Noah!
hello2(greeting="Hi") # Hi, World!
hello2("Beata", "Hi") # Hi, Beata!

收集参数

def print_params(*params):
   print(params)

print_params(1,2,3) # (1, 2, 3)

def print_params(title, *params):
    print(title)
    print(params) 

print_params("Title", 1, 2, 3) 
# Title
# (1, 2, 3)

def print_pair(**kp):
    print(kp)

print_pair(x=1, y=2, z=3) # {'x': 1, 'y': 2, 'z': 3}

def print_all(title, *params, **kp):
    print(title)
    print(*params)
    print(kp)

print_all("Title", 1, 2, 3, x=1, y=2, z=3)
# Title
# 1 2 3
# {'x': 1, 'y': 2, 'z': 3}      

反转参数

def add(x, y):
    'Add x and y and print it'
    print("{0}+{1}={2}".format(x, y, x+y))

add(4, 5)
nums = [4, 5]
add(*nums)

params = {"greeting": "Hi", "name": "Dear"}

hello(**params)
hello2(**params)

方法相关

print(callable(nums)) # False
print(callable(hello)) # True

print("-"*100)
print(add.__doc__)
print("-"*100)
help(add)
print("-"*100)  

Python

这篇文章: 有用 无用
创建 2018-10-16 16:45:05 / 更新 2018-10-16 16:45:05