python的面向物件以及面向物件的設計
阿新 • • 發佈:2018-12-10
# 在程式中:務必保證先定義類,後產生物件 # #程式中類的用法 # .:專門用來訪問屬性,本質操作的就是__dict__ # OldboyStudent.school #等於經典類的操作OldboyStudent.__dict__['school'] # OldboyStudent.school='Oldboy' #等於經典類的操作OldboyStudent.__dict__['school']='Oldboy' # OldboyStudent.x=1 #等於經典類的操作OldboyStudent.__dict__['x']=1 # del OldboyStudent.x #等於經典類的操作OldboyStudent.__dict__.pop('x') #程式中的物件 #呼叫類,或稱為例項化,得到物件 # s1=OldboyStudent() # s2=OldboyStudent() # s3=OldboyStudent() # http://www.cnblogs.com/linhaifeng/articles/6182264.html#_label1 # dog1={ "name":"元昊", # "gender":"母的", # "type":"藏獒", # # } # dog2={ "mingzi":"元昊", # "gender":"母的", # "type":"藏獒", # } # person1={ "name":"pl", # "gender":"super man", # "type":"人", # } def dog(name,gender,type): def jiao(dog): print("一條狗[%s],汪汪汪"%dog['name']) def chi_shi(dog): print("一條[%s] 正在吃屎"%dog['type']) def wan_shua(dog): print("一條[%s][%s]狗正在玩耍"%(dog['gender'],dog['name'])) def init(name,gender,type): dog1 = {"name": "元昊", "gender": "母的", "type": "藏獒", 'jiao':jiao, 'chi_shi':chi_shi, 'wan_shua':wan_shua, } return dog1 res=init(name,gender,type) return res d1=dog('元昊','母','中華田園犬') d2=dog('alxe','公','藏獒') d3=dog('sb','women','taidi') print(d1) print(d2) print(d3) d1['jiao'](d1) d2['chi_shi'](d2) d3['wan_shua'](d3) # 把一類事物的相同特徵和動作整合到一起就是類 #類是一個抽象的概念 #物件:就是基於類而建立的一個具體的事物(具體存在的) #也就是特徵和動作整合到一起
python 面向物件的設計
#http://www.cnblogs.com/linhaifeng/articles/6182264.html # def school(name,addr,type): # def init(name,addr,type): # sch = { # 'name': name, # 'addr': addr, # 'type': type, # 'kao_shi': kao_shi, # 'zhao_sheng': zhao_sheng, # } # return sch # def kao_shi(school): # print('%s 學校正在考試' % school['name']) # def zhao_sheng(school): # print('%s %s %s 正在招生' % (school['type'], school['name'],school['addr'])) # return init(name,addr,type) # s1=school('old boy','tian cai','私立學校') # print(s1) # print(s1['name']) # s1['zhao_sheng'](s1) # s2=school('清華','北大','哈弗') # s2['zhao_sheng'](s2) #類 class Dog: def __init__(self,name,type,addr): self.name=name self.type=type self.addr=addr def bark(self): print("一條名叫%s %s狗正在%s上吊自殺"%(self.name,self.type,self.addr)) dog1=Dog('alex','female','阜師院') print(dog1.__dict__) dog1.bark() print("\\\\\\"*20) #屬性 #類是用來描述一類食物,類的物件指的是這一類事物中的一個個體 #屬性:資料屬性 就是變數,函式屬性:在面向物件裡通常稱為方法 #類和物件均用 ‘點’ 來訪問自己的屬性 class Chinese: dang='中國人愛共產黨' def sui_di_tu_tan(self): print("隨地吐痰") print(Chinese.dang) Chinese.sui_di_tu_tan("wo") print(Chinese.__dict__['dang']) Chinese.__dict__['sui_di_tu_tan']('wo') class Chinese: def __init__(self,name,age,gender): print("初始化函式") self.mingzi=name self.nianji=age self.xingbie=gender def sui_di_tu_tan(self): print('%s已經%s但是還在吐痰'%(self.mingzi,self.nianji)) def cha_dui(self): print('他插隊到了前面') # cha_dui('小明') p1=Chinese('小方',22,'female')#實列 類名 加括號的形式 print(p1.__dict__) print(p1.nianji)#呼叫單個的 用點來代替以上類中的前一個 p1.sui_di_tu_tan() p2=Chinese('小明',18,'男的') print(p2.__dict__) #類屬性 函式屬性