1. 程式人生 > >python 學習彙總59:高階函式與類的關係(初級學習- tcy)

python 學習彙總59:高階函式與類的關係(初級學習- tcy)

 目錄: 
1. class定義
2. 內部類
3.外部定義函式
4.高階函式與類的關係
5.物件記憶體管理
6.類作用域
7.使用輸出引數
8.類屬性
9.類特性
10.描述符
11.檢視類屬性
12.繼承
13.型別檢測測試,檢視父子類
15.元類
16.基類
17.類裝飾器
18.Enum類
其他參考本人博文。 

高階函式與類的關係 建立日期2018/8/7 修改時間2018/11/19

 

1.建立高階函式:

def linear(a, b):
def result(x):
return a * x + b
return result

# 測試:
taxes=linear(0.3,2)
taxes(10e6)#3000002.0
2.建立類:缺點是速度稍慢,程式碼稍長 : 
class linear:
def __init__(self, a, b):
self.a, self.b = a, b
def __call__(self, x):
return self.a * x + self.b

# 呼叫
taxes = linear(0.3, 2)
taxes(10e6) == 0.3 * 10e6 + 2#True
taxes(10e6) # 3000002.0
3.繼承分享他們的簽名:  
class exponential(linear):
# __init__ inherited #不用再初始化
def __call__(self, x): #實現新功能
return self.a * (x ** self.b)

#呼叫
a=exponential(2,3)
a(2) #16 =2*(2**3) 
4.可以封裝幾種方法: 
class counter:
value = 0
def set(self, x):
self.value = x

def up(self):
self.value = self.value + 1

def down(self):
self.value = self.value - 1

count = counter()