十、對面向物件新的理解
阿新 • • 發佈:2018-12-09
看了一個視訊,顛覆了之前對面向物件設計的理解,程式設計真的的很神奇,他的部落格:
之前以為面向物件就是class A(){},現在知道了只用函式也可以面向物件程式設計。
面向過程、面向物件、函數語言程式設計只是不同的程式設計正規化吧,本身沒有好壞之分,看用的人了。
# -*- coding:utf-8 -*- dog1={ 'name':'aa', 'gender':'公', 'type':'藏獒' } dog2={ 'name':'bb', 'gender':'公', 'type':'藏獒' } def eat(dog): print('the %s is eating'%dog['name']) def jiao(dog): print('the %s is jiao'%dog['type']) eat(dog1) eat(dog2) jiao(dog1) jiao(dog2) ########################################## dog1={ 'name':'aa', 'gender':'公', 'type':'藏獒' } dog2={ 'name':'bb', 'gender':'公', 'type':'藏獒' } person1={ 'name':'cc', 'gender':'女', 'type':'人' } def eat(dog): print('the %s is eating'%dog['name']) def jiao(dog): print('the %s is jiao'%dog['type']) eat(dog1) eat(dog2) jiao(dog1) jiao(dog2) eat(person1) jiao(person1)#這時候人也可以呼叫狗的方法,顯然不合適,應該把狗的方法和狗繫結到一塊,想到了函式的封裝 ######################################################## def dog(): def eat(dog): print('the %s is eating'%dog['name']) def jiao(dog): print('the %s is jiao'%dog['type']) dog1 = { 'name': 'aa', 'gender': '公', 'type': '藏獒', 'eat': eat,#函式名 'jiao': jiao } return dog1 d1=dog() print(d1)#{'gender': '公', 'jiao': <function dog.<locals>.jiao at 0x000000AB5F69CA60>, 'type': '藏獒', 'name': 'aa', 'eat': <function dog.<locals>.eat at 0x000000AB5F69C9D8>} d1['jiao'](d1)#the 藏獒 is jiao,函式要有引數,這個引數就是他本身d1 ######################################################################## ######現在的問題是隻有一條狗,這條狗d1在函式裡已經寫死了,如果有另外的狗還要重複程式碼,不能寫死就從外面傳進來################ def dog(name,gender,type): def eat(dog): print('the %s is eating'%dog['name']) def jiao(dog): print('the %s is jiao'%dog['type']) dog1 = { 'name': name, 'gender': gender, 'type': type, 'eat': eat,#函式名 'jiao': jiao } return dog1 d1=dog('dd','公','京巴')#產生新的狗 d2=dog('ee','母','京巴2')#產生新的狗 print(d1)#{'gender': '公', 'jiao': <function dog.<locals>.jiao at 0x000000AB5F69CA60>, 'type': '藏獒', 'name': 'aa', 'eat': <function dog.<locals>.eat at 0x000000AB5F69C9D8>} d1['jiao'](d1)#the 藏獒 is jiao,函式要有引數,這個引數就是他本身d1 d2['jiao'](d2) ###################################################### #再做一個小小的改進,加了一個Init函式用來初始化,這樣dog()函式的結構很清晰,包含了三個功能明確的函式 def dog(name,gender,type): def eat(dog): print('the %s is eating'%dog['name']) def jiao(dog): print('the %s is jiao'%dog['type']) def init(name,gender,type):#用來初始化 dog1 = { 'name': name, 'gender': gender, 'type': type, 'eat': eat, # 函式名 'jiao': jiao } return dog1 return init(name,gender,type) d1=dog('dd','公','京巴') d2=dog('ee','母','京巴2') print(d1)#{'gender': '公', 'jiao': <function dog.<locals>.jiao at 0x000000AB5F69CA60>, 'type': '藏獒', 'name': 'aa', 'eat': <function dog.<locals>.eat at 0x000000AB5F69C9D8>} d1['jiao'](d1)#the 藏獒 is jiao,函式要有引數,這個引數就是他本身d1 d2['jiao'](d2)