1. 程式人生 > >python之旅-----函式與類

python之旅-----函式與類

1. 定義函式

def greet_user():
    """顯示簡單的問好"""
    print("hello")
greet_user()

2. 引數傳遞

#以位置順序來確定實參和形參的對應關係
def greet_user(name,age):
    """顯示簡單的問好"""
    print("hello!  "+ name)
    print("your age is "+ age)
greet_user("yanglujian","27")

#關鍵字來確定引數傳遞的關係
def greet_user(name,age):
    """顯示簡單的問好"""
    print("hello!  "+ name)
    print("your age is "+ age)
greet_user(name="yanglujian",age="27")

#引數預設值
def greet_user(name,age="25"):
    """顯示簡單的問好"""
    print("hello!  "+ name)
    print("your age is "+ age)
greet_user(name="yanglujian",age="27")
greet_user(name="wanglinbin")

#有返回的函式
def greet_user(name,age="25"):
    """顯示簡單的問好"""
    print("hello!  "+ name)
    print("your age is "+ age)
    return "hello  "+ name + "  age:"+ age
greet_user(name="yanglujian",age="27")
print(greet_user(name="wanglinbin"))
#資料結構作為引數傳遞,值傳遞
users = ['yanglujian','wanglinbin','taojinchen']
users2 = users[:]
def greet_users(usrs):
    for usr in usrs:
        print("hello "+ usr)
    usrs[0] = "new element"
greet_users(users[:])  # 將佇列複製一份在將副本的引用傳入函式
print(users)
print(users2)


#資料結構作為引數傳遞,引用傳遞
users = ['yanglujian','wanglinbin','taojinchen']
def greet_users(usrs):
    for usr in usrs:
        print("hello "+ usr)
    users[0] = "new element"
greet_users(users)
print(users)
# 將任意長度引數傳入
def greet_user(*names):
    """顯示簡單的問好"""
    for name in names:
        print("hello  "+ name)

greet_user("yanglujian","wanglinbin",'taojincheng')

3. 模組化

#匯入另外模組的函式,並且將匯入的函式在該模組中重新命名
from greet import greet_user as  hello

hello("yanglujian","wanglinbin","taojincheng")
#匯入另外模組,並且將該模組重新命名
import greet as hello

hello.greet_user("yanglujian","wanglinbin","taojincheng")
hello.greet_anmail("楊","鑑定","你好嗎")