1. 程式人生 > >python 學習彙總21:函式用作引數( tcy)

python 學習彙總21:函式用作引數( tcy)


函式用作引數   2018 / 11 / 14
    
====================================================================
    
1.1.將函式作為引數;# 以字串的形式執行函式
    
import math
    
items = {'number': 42, 'text': "hello word"}
nums = [1, 2, 3, 4]
    
items['func'] = abs               # 將函式作為引數傳入
items['mod'] = math
items['error'] = ValueError
items['append'] = nums.append
    
print(items)
    
# {'number': 42, 'text': 'hello word', 'func': <built-in function abs>, 
# 'mod': <module 'math' (built-in)>,'error': <class 'ValueError'>, 
# 'append': <built-in method append of list object at 0x0000000000596248>}
    
print(items['func'](-45))          # 45 將函式作為引數;以字串的形式執行函式
print(items['mod'].sqrt(4))       # 2.0
    
try:
    x = int('a lot')
except items['error'] as e:
    print("couldn't convert")
    
items['append'](100)
print(nums)  # [1, 2, 3, 4, 100]
#
================================================================
1.2.將字串轉換成字母數字
    
line = 'goog,100,490.1'
field_types = [str, int, float]  # 轉換函式
raw_fields = line.split(',')
    
fields = [type_function(val) for type_function, val in zip(field_types, raw_fields)]
    
print(fields)  # ['goog', 100, 490.1]
    
================================================================
2.將類作為引數傳入
    
class MyClass():
    def __init__(self, x):
        self.x = x
    
    def set_x(self, x):
        self.x = x
    
    def get_x(self):
        return self.x
    
    def show(self, y):
        print('show x+y=', self.x + y)
    
# 普通類應用
y = 1000
a1 = MyClass(100)
print('self.x=', a1.x)
a1.show(y)
a1.set_x(200)
print('self.x=', a1.x)
a1.show(y)
print('+++++++++++++++++++++++++++++++++++++++++++++++++')
#
class_items = {'class': MyClass}
class_values = [1000, 100, 200]
    
a2 = class_items['class']
class_items['instance_a2'] = a2(class_values[1])
    
# 不要這樣寫,由於類名稱空間和全域性名稱空間的不同,僅當前起作用
# class_items['attribute_x']=class_items['instance_a2'].x
    
# 正確用法:類例項屬性必須經由例項直接訪問,或用get函式取得;類方法則都可以;
class_items['method_set_x'] = class_items['instance_a2'].set_x
# ***********************************************
print('self.x=', class_items['instance_a2'].x)
class_items['instance_a2'].show(class_values[0])
    
class_items['instance_a2'].set_x(class_values[2])
    
print('self.x=', class_items['instance_a2'].x)
class_items['instance_a2'].show(class_values[0])
    
# 結果顯示
# self.x= 100
# show x+y= 1100
# self.x= 200
# show x+y= 1200
# +++++++++++++++++++++++++++++++++++++++++++++++++
# self.x= 100
# show x+y= 1100
# self.x= 200
# show x+y= 1200
    
==================================================================