下面列舉了4種不同情況下 python的函式引數使用方法,以及執行結果
# 函式的引數
# 定義必備引數,也就是說 沒有預設值的,只能靠引數的傳入
def fun1(string):
print("what you say is:",string)
return
# 定義了預設的引數
def fun2(string = 'hi'):
print("what you say is:",string)
return
# 定義關鍵字引數
def fun3(string2='hello',string1='world'):
print("what you say is:",string2+string1)
return
# 定義不定長引數
def fun4(arg1,*arg2):
print(arg1)
for i in arg2:
print(i)
return
fun1("hello,world")
fun2()
fun2("hello,hello")
fun3(string1='hihihi',string2='wwwww')
fun4(10,1,2,3,4,5,6,7)
執行結果如下:
what you say is: hello,world
what you say is: hi
what you say is: hello,hello
what you say is: wwwwwhihihi101
2345
67
2.1 首先嘗試一下 類的建立
# 類的建立
class student:
student_count = 0
def __init__(self,name,age):
self.name = name
self.age = age
student.student_count += 1
def dis_student(self):
print("student name:",self.name,",student age:",self.age)
student1 = student('chen',20)
student2 = student('xiu',18)
student1.dis_student()
student2.dis_student()
# 在類的外部,也可以訪問類中的變數
print("total student:",student.student_count)
執行結果如下:
student name: chen ,student age: 20
student name: xiu ,student age: 18
total student: 2
2.2 類的繼承
#類的繼承
class people:
def __init__(self,height,age):
self.height = height
self.age = age
def dis_height(self):
print("height:",self.height)
def set_age(self,age):
self.age = age
def dis_age(self):
print("age:",self.age)
# 在子類的括號中,寫上父類的類名,就表示繼承了父類
class student(people):
def __init__(self,name,age,school_name,height = 30):
self.height = height # 父類的變數還需要在子類中初始化一下
self.name = name
self.age = age
self.school_name = school_name
def dis_student(self):
print("school name:",self.school_name)
student = student('chene',20,'beijing',40)
# 呼叫子類中的函式
student.dis_student()
# 呼叫父類中的函式
student.dis_height()
student.dis_age()
student.set_age(10)
student.dis_age()
執行結果如下:
school name: beijing
height: 40
age: 20
age: 10
Python 函式及引數
函式引數定義的順序必須是 必選引數 預設引數 可變引數 命名關鍵字引數和關鍵字引數。使用遞迴函式需要注意防止棧溢位。在計算機中,函式呼叫是通過棧 stack 這種資料結構實現的,每當進入乙個函式呼叫,棧就會加一層棧幀,每當函式返回,棧就會減一層棧幀。由於棧的大小不是無限的,所以,遞迴呼叫的次數過多,...
Python中的函式定義及引數
1 函式必須先宣告在使用,自定義函式採用關鍵字def,返回語句return,同時可以支援pass語句佔位,標明函式為空函式 函式 自定義求絕對值函式 def myabs x ifnot isinstance x int,float raise typeerror illigel argument.i...
Python中的函式(def)及引數傳遞
抽象 函式 1 callable 判斷乙個物件是否可以被呼叫 x 1 def y return none callable y y可以被呼叫 callable x x不可以被呼叫 2 當函式沒有return時 函式將預設返回none 3 放在函式開頭的字串成為文件字串 如下 def square x...