Python函數調用的幾種方式(類里面,類之間,類外面)
第一種 是在class內部,方法之間的互相調用
舉一個簡單的例子
class cat():
def __init__(self,age):
cat.age = age
def show_color(self):
print("The color of the cat is white")
def show_age(self):
self.show_color()
print("The age of the cat is "+str(self.age))
Ragdoll = cat(2)
Ragdoll.show_age()結果為

這里我只用實例Ragdoll調用了show_age方法,但因為在show_age中調用了show_color方法,所以兩個方法最后都執(zhí)行了
類里面的方法想調用另外一個方法,需要在方法體中用self.方法名的方式來調用
同樣,類里面的方法想調用類的屬性,需要用self.屬性名的方式
第二種 是在類的外面,def函數之間的彼此調用
還是來看一個簡單的例子
def show_num(num):
print(num)
def test(num):
if num>3:
show_num(num)
test(4)結果為

在類外面的函數之間,只需要函數名就可以調用彼此
另外要記得參數列表保持一致,如果你要調用的函數參數列表中有多個參數,那么自身這個函數的參數列表中也要有那些參數
以下是錯誤示范
def create_cat(color,age):
print("The age and color of the cat are"+str(age)+color)
def show_cat():
create_cat(color,age)
show_cat()結果是

正確的函數調用是這樣
def create_cat(color,age):
print("The age and color of the cat are "+str(age)+" and "+color)
def show_cat(color,age):
create_cat(color,age)
show_cat("white",3)結果是

第三種 是在類外面的函數,調用在類里面的方法
class cat():
def __init__(self,age):
self.age = age
def age_increase(self):
self.age += 1
print("the age of the cat is "+str(self.age))
def year():
Ragdoll = cat(3)
Ragdoll.age_increase()
year()結果為

創(chuàng)建該類的實例對象,再通過實例調用方法,最后運行函數即可
class cat():
def __init__(self,age):
self.age = age
self.color = "white"
def age_increase(self):
self.age += 1
print("the age of the cat is "+str(self.age))
def year():
Ragdoll = cat(3)
Ragdoll.age_increase()
print(Ragdoll.color)
year() 在函數中直接用實例調用屬性,獲取屬性值也是可以的結果為

第四種 是不同的類之間的方法的彼此調用
class cat():
def __init__(self,age1):
self.age1 = age1
def show_age(self):
print("the age of the cat is "+str(self.age1))
class dog():
def __init__(self,age2):
self.age2 = age2
def show_cat_age(self):
Ragdoll = cat(3)
Ragdoll.show_age()
Husky = dog(2)
Husky.show_cat_age()結果為

而如果想在這個類里面調用其他類里面的屬性值,則需要這樣做
class cat():
def __init__(self,age1):
self.age1 = age1
self.color = "white"
def show_age(self):
print("the age of the cat is "+str(self.age1))
class dog():
def __init__(self,age2,Ragdoll):
self.age2 = age2
self.Ragdoll = Ragdoll
def show_cat_age(self,Ragdoll):
Ragdoll = cat(3)
Ragdoll.show_age()
print(self.Ragdoll.color)
if self.Ragdoll.age1 > self.age2:
print("the cat is older than the dog")
def run():
Ragdoll = cat(3)
Husky = dog(2,Ragdoll)
Husky.show_cat_age(Ragdoll)
run()結果為

需要將對象作為參數放入類里面
到此這篇關于Python函數調用的幾種方式(類里面,類之間,類外面)的文章就介紹到這了,更多相關Python函數調用內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

