Python開發【第七章】:Python物件導向進階,python物件導向

來源:互聯網
上載者:User

Python開發【第七章】:Python物件導向進階,python物件導向
1、靜態方法

  通過@staticmethod裝飾器即可把其裝飾的方法變為一個靜態方法,什麼是靜態方法呢?其實不難理解,普通的方法,可以在執行個體化後直接調用,並且在方法裡可以通過self.調用執行個體變數或類變數,但靜態方法是不可以訪問執行個體變數或類變數的,一個不能訪問執行個體變數和類變數的方法,其實相當於跟類本身已經沒什麼關係了,它與類唯一的關聯就是需要通過類名來調用這個方法

#靜態方法class Schoolmate(object):    def __init__(self, name):        self.name = name    @staticmethod    # 把eat方法變為靜態方法    def eat(self):        print("%s is eating" % self.name)p= Schoolmate("LianZhiLei")p.eat()# Traceback (most recent call last):#   File "C:/Users/L/PycharmProjects/s14/class/Day7/staticmothod.py", line 16, in <module>#     p.eat()#TypeError: eat() missing 1 required positional argument: 'self'

上面的調用會出以下錯誤,說是eat需要一個self參數,但調用時卻沒有傳遞,沒錯,當eat變成靜態方法後,再通過執行個體調用時就不會自動把執行個體本身當作一個參數傳給self了。

想讓上面的代碼可以正常工作有兩種辦法

  • 調用時主動傳遞執行個體本身給eat方法,即p.eat(p) 
  • 在eat方法中去掉self參數,但這也意味著,在eat中不能通過self.調用執行個體中的其它變數了
#靜態方法class Schoolmate(object):    def __init__(self, name):        self.name = name    @staticmethod    # 把eat方法變為靜態方法    def eat(self):        print("%s is eating" % self.name)p= Schoolmate("LianZhiLei")p.eat(p)#LianZhiLei is eating#靜態方法class Schoolmate(object):    def __init__(self, name):        self.name = name    @staticmethod    # 把eat方法變為靜態方法    def eat():        print("is eating")p= Schoolmate("LianZhiLei")p.eat()#is eating

  

2、類方法

  類方法顧名思義跟類有關,類方法通過@classmethod裝飾器實現,類方法和普通方法的區別是, 類方法只能訪問類變數,不能訪問執行個體變數

#類方法class Schoolmate(object):    def __init__(self, name):        self.name = name    @classmethod   # 把eat方法變為類方法    def eat(self):        print("%s is eating" % self.name)p= Schoolmate("LianZhiLei")p.eat()# Traceback (most recent call last):#   File "C:/Users/L/PycharmProjects/s14/class/Day7/classmothod.py", line 15, in <module>#     p.eat()#   File "C:/Users/L/PycharmProjects/s14/class/Day7/classmothod.py", line 12, in eat#     print("%s is eating" % self.name)# AttributeError: type object 'Schoolmate' has no attribute 'name'

執行報錯如下,說schoolmat沒有name屬性,這是因為name是個執行個體變數,類方法是不能訪問執行個體變數的,只能訪問類變數

#類方法class Schoolmate(object):    name = ("Schoolmat的類變數")    def __init__(self, name):        self.name = name    @classmethod   # 把eat方法變為類方法    def eat(self):        print("%s is eating" % self.name)p= Schoolmate("LianZhiLei")p.eat()# Schoolmat的類變數 is eating

此時可以定義一個類變數,變數名為name即可解決

 

3、屬性方法

  屬性方法的作用就是通過@property把一個方法變成一個靜態屬性,這個蠻有用的,後面課程會涉及到,先看代碼

#屬性方法class Schoolmate(object):    name = ("Schoolmat的類變數")    def __init__(self, name):        self.name = name    @property       # 把eat方法變為屬性方法    def eat(self):        print("%s is eating" % self.name)p= Schoolmate("LianZhiLei")p.eat# Traceback (most recent call last):#   File "C:/Users/L/PycharmProjects/s14/class/Day7/property.py", line 17, in <module>#     p.eat()# TypeError: 'NoneType' object is not callable

調用會出以下錯誤, 說NoneType is not callable, 因為eat此時已經變成一個靜態屬性了, 不是方法了, 想調用已經不需要加()號了,直接d.eat就可以了

#屬性方法class Schoolmate(object):    name = ("Schoolmat的類變數")    def __init__(self, name):        self.name = name    @property       # 把eat方法變為屬性方法    def eat(self):        print("%s is eating" % self.name)p= Schoolmate("LianZhiLei")p.eat#LianZhiLei is eating

  好吧,把一個方法變成靜態屬性有什麼卵用呢?既然想要靜態變數,那直接定義成一個靜態變數不就得了嗎?well, 以後我們會遇到靜態變數不固定的情況,不能簡單通過定義靜態屬性來實現的, 比如 ,你想知道一個航班當前的狀態,是到達了、延遲了、取消了、還是已經飛走了, 想知道這種狀態你必須經曆以下幾步:串連航空公司API查詢、對查詢結果進行解析 、返回結果給你的使用者;因此這個status屬性的值是一系列動作後才得到的結果,所以你每次調用時,其實它都要經過一系列的動作才返回你結果,但這些動作過程不需要使用者關心, 使用者只需要調用這個屬性就可以,明白了嗎?

#屬性方法執行個體class Flight(object):    def __init__(self,name):        self.flight_name = name    def checking_status(self):        print("checking flight %s status " % self.flight_name)        return  1    @property    def flight_status(self):        status = self.checking_status()        if status == 0 :            print("flight got canceled...")        elif status == 1 :            print("flight is arrived...")        elif status == 2:            print("flight has departured already...")        else:            print("cannot confirm the flight status...,please check later")f = Flight("CA980")f.flight_status

cool , 那現在我只能查詢航班狀態, 既然這個flight_status已經是個屬性了, 那我能否給它賦值呢?試試吧 

f = Flight("CA980")f.flight_statusf.flight_status = 2# checking flight CA980 status # Traceback (most recent call last):# flight is arrived...#   File "C:/Users/L/PycharmProjects/s14/class/Day7/flight_status.py", line 31, in <module>#     f.flight_status = 2# AttributeError: can't set attribute

輸出, 說不能更改這個屬性,我擦。。。。,怎麼辦怎麼辦。。。當然可以改, 不過需要通過@proerty.setter裝飾器再裝飾一下,此時 你需要寫一個新方法, 對這個flight_status變更。

#屬性方法class Flight(object):    def __init__(self, name):        self.flight_name = name    def checking_status(self):        print("checking flight %s status " % self.flight_name)        return 1    @property    def flight_status(self):        status = self.checking_status()        if status == 0:            print("flight got canceled...")        elif status == 1:            print("flight is arrived...")        elif status == 2:            print("flight has departured already...")        else:            print("cannot confirm the flight status...,please check later")    @flight_status.setter  # 修改     執行修改操作時觸發    def flight_status(self, status):        status_dic = {        0: "canceled",        1:"arrived",        2: "departured"        }        print("\033[31;1mHas changed the flight status to \033[0m", status_dic.get(status))    @flight_status.deleter  # 刪除    def flight_status(self):        print("status got removed...")f = Flight("CA980")f.flight_status = 0  # 觸發@flight_status.setter 只執行setter裝飾的代碼del f.flight_status  #  觸發@flight_status.deleter 只執行deleter裝飾的代碼

執行相應的操作,觸發相應的裝飾器,此時不會再觸發原來的屬性,只執行裝飾器下面的代碼,需要做相應的操作可在代碼塊裡添加(修改,刪除);只是觸發了而已,裝飾器並沒有做什麼操作

 

4、類的特殊成員方法

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.