Python 物件導向之一,python物件導向

來源:互聯網
上載者:User

Python 物件導向之一,python物件導向

Python 物件導向之 類與屬性

    今天接觸了一下物件導向,發現物件導向和之前理解的簡直就是天壤之別,在學Linux的時候,一切皆檔案,現在學物件導向了,so,一切皆對象。

    之前不是一直在學的用面向函數編程,用函數就可以搞定一切了,但是為啥要用物件導向?物件導向呢,大大的提高了程式的可擴充性,面對不停的需求改變的時候,物件導向的優越性就展現出來了,先從面向函數來向物件導向進行過度。

先舉一個例子:

# def dog(name,gender,type):#     # 狗的動作#     def jiao(dog):#         print('一條狗[%s],汪汪汪' % dog['name'])  #此處可以與函數名dog或者與字典的傳回值do同名都可以(最好還是要以傳回值相同)#     def chi_fan(dog):#         print('一條[%s] 正在吃飯' % dog['type'])#     dog = {#         'name':name,#         'gender': gender,#         'type': type,#         'jiao':jiao,#         'chi_shi':chi_fan,#     }#     return dog# d1=dog('牛逼','公','中華犬')
輸出的結果:
#{'name': '牛逼', 'gender': '公', 'type': '中華犬', 'jiao': <function dog.<locals>.jiao at 0x005912B8>, 'chi_fan': <function dog.<locals>.chi_shi at 0x00591270>}

從上面的例子可以看出:定義了一個dog函數,在這個函數內呢又定義了函數jiao和 chi_fan 兩個函數,還定義了一個字典,在這個字典中呢有定義dog的資料屬性,比如:名字,性別等,還有函數屬性 叫和吃飯,在函數最後有一個傳回值return 返回的呢是dog 這個字典,列印d1的數值就會發現:得到的是一個字典類型的資料,其中函數屬性返回的是函數的記憶體位址。

在此基礎上進行改進:

def dog(name,gender,type):#     # 狗的動作#     def jiao(dog):#         print('一條狗[%s],汪汪汪' % dog['name'])#     def chi_fan(dog):#         print('一條[%s] 正在吃飯' % dog['type'])#     def init(name,gender,type):#狗的屬性和狗的方法(將傳回值也做成一個方法來使用)#         dog1 = {#             'name':name,#             'gender': gender,#             'type': type,#             'jiao':jiao,#             'chi_shi':chi_fan,#         }#         return dog1#     return init(name,gender,type)  # (將函數名當參數進行傳遞)## d1=dog('牛逼','公','中華犬')# print(d1)# d1['jiao'](d1)   #jiao 函數需要傳入參數,參數為d1這個狗輸出結果:一條狗[牛逼],汪汪汪

這一次是在之前的基礎上把傳回值做成一個init的函數通過這個函數來執行字典裡面的內容,若是要調用定義def dog中的方法,調用方式為:d1['jiao'](d1) #調用字典的值加括弧進行運此函數。

是不是還是面向函數實現了把dog 的屬性和方法封裝在函數中實現了,好了接下來用物件導向來實現上述的功能:

class Dog:    def __init__(self,name,gender,type):        self.name = name        self.gender = gender        self.type = type    def jaio(self,):        print('一條叫%s 的狗在大聲的叫'%(self.name))    def chi_fan(self,):        print('一條叫%s 的狗在吃飯'%(self.name))d1 = Dog('牛逼','male','公')print(d1) # <__main__.Dog object at 0x004D6690>print(d1.__dict__) # {'name': '牛逼', 'gender': 'male', 'type': '公'}d1.chi_fan() # 一條叫牛逼 的狗在吃飯

好現在總結一下,類:就是把一類事物的相同特徵和動作整合在一起就是類,類就是一個抽象概念。對象:就是基於類建立的一個具體的事物(具體存在的),也是把動作和特徵結合在一起。

接下來看一下類的資料屬性和函數屬性:

class Chinese:    '中國人的類'    ren='中國人'    def watch_tv(self):        print('好牛逼的劇')    def cha_dui(self):        print('插到了前面')print(Chinese.ren)Chinese.watch_tv('kjk')Chinese.cha_dui('就是你')#print(dir(Chinese)) #查看存在的方法print(Chinese.__dict__) #查看類的屬性字典print(Chinese.__dict__['ren'])Chinese.__dict__['watch_tv'](1)Chinese.__dict__['cha_dui'](1)#輸出結果為:中國人好牛逼的劇插到了前面['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'cha_dui', 'ren', 'watch_tv']{'__module__': '__main__', '__doc__': '中國人的類', 'ren': '中國人', 'watch_tv': <function Chinese.watch_tv at 0x008112B8>, 'cha_dui': <function Chinese.cha_dui at 0x00811270>, '__dict__': <attribute '__dict__' of 'Chinese' objects>, '__weakref__': <attribute '__weakref__' of 'Chinese' objects>}中國人好牛逼的劇插到了前面

類屬性的增刪改查:

class Chinese:    country='China'    def __init__(self,name):        self.name=name    def play_ball(self,ball):        print('%s 正在打 %s' %(self.name))#查看print(Chinese.country)## #修改Chinese.country='Japan'print(Chinese.country)#p1=Chinese('alex')print(p1.__dict__)#返回的是p1對象中init中儲存的字典資料屬性print(p1.country) #首先在p1的資料屬性中找若此數值不存在則在類的資料屬性中找## #增加Chinese.ren='中國人'#print(Chinese.ren)print(p1.ren) #首先在p1的資料屬性中找若此數值不存在則在類的資料屬性中找# #刪除del Chinese.rendel Chinese.country## print(Chinese.__dict__)# print(Chinese.country)  #AttributeError: type object 'Chinese' has no attribute 'country'#增加方法def eat_food(self,food):    print('%s 正在吃%s' %(self.name,food))#Chinese.eat=eat_food  #{'__module__': '__main__', '__init__': <function Chinese.__init__ at 0x021E1300>, 'play_ball': <function Chinese.play_ball at 0x021E12B8>, '__dict__': <attribute '__dict__' of 'Chinese' objects>, '__weakref__': <attribute '__weakref__' of 'Chinese' objects>, '__doc__': None, 'eat': <function eat_food at 0x021E1348>}#print(Chinese.__dict__)p1.eat('飯') #alex 正在吃飯#

執行個體屬性的增刪改查:

class Chinese:    country='China'    def __init__(self,name):        self.name=name    def play_ball(self,ball):        print('%s 正在打 %s' %(self.name,ball))p1=Chinese('牛逼') #執行個體化一個對象p1print(p1.__dict__) #列印p1中存在的所有屬性(執行個體化對象中只存在數值型屬性)#查看print(p1.name)print(p1.play_ball) # bound method Chinese.play_ball of <__main__.Chinese object at 0x00426690>># #增加p1.age=18print(p1.__dict__)print(p1.age)### #修改p1.age=19print(p1.__dict__)print(p1.age)## #刪除del p1.ageprint(p1.__dict__)

擷取類屬性和執行個體化的屬性舉例:

class Chinese:    country='China'    l=['a','b']    def __init__(self,name):        self.name=name    def play_ball(self,ball):        print('%s 正在打 %s' %(self.name,ball))p1=Chinese('sb')print(p1.l) #現去p1的init中找,若沒有就會去類Chinese中去找類的資料屬性p1.l=[1,2,3] #是給執行個體化對象p1中添加一個資料屬性 'l': [1, 2, 3]print(Chinese.l) #['a', 'b']print(p1.__dict__) #{'name': 'sb', 'l': [1, 2, 3]}p1.l.append('c')print(p1.__dict__) #{'name': 'sb', 'l': [1, 2, 3, 'c']}print(Chinese.l) #['a', 'b']country='中國-------------------'class Chinese:    country='中國'    def __init__(self,name):        self.name=name        print('--->',country)    def play_ball(self,ball):        print('%s 正在打 %s' %(self.name,ball))#print(Chinese.__dict__)  # {'__module__': '__main__', 'country': '中國', '__init__': <function Chinese.__init__ at 0x006E1300>, 'play_ball': <function Chinese.play_ball at 0x006E12B8>, '__dict__': <attribute '__dict__' of 'Chinese' objects>, '__weakref__': <attribute '__weakref__' of 'Chinese' objects>, '__doc__': None}#print(Chinese.country)  #中國p1=Chinese('sb') #---> 中國-------------------print('執行個體--------》',p1.country) #執行個體--------》 中國#注意:通過點(.)來訪問變數時在類class中去尋找,而一般變數不是通過執行個體化對象或類名點的方式去訪問,則這個是在類的外面去尋找這個變數。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.