python2學習------基礎文法2(類、類的繼承、類成員函數、防禦式編程)

來源:互聯網
上載者:User

標籤:def   turn   range   學習   文法   python2   test   func   message   

1、類的定義以及執行個體化

# 類定義class p:    """ this is a basic class """    def __init__(self): # 類成員函數需要傳入self關鍵字        """ this is a init function of basic class """        print "this is a init function ... ";    def sub(self,a,b): # 類成員函數需要傳入self關鍵字        """ this is a common function of basic class """        return a-b;# 類執行個體化a=p();# 調用類方法print a.sub(40,5); # -1

 

2、類的繼承

# 繼承類class m(p): # 參數為需要被繼承的類的名稱    """ this is a sub-class of basic class """    def __init__(self):# 專有函數(函數名首尾帶有雙底線)        print "sub class init function ... ";        self.__test();            def loopOutputFun(self,n):        if n<0:            print n,"is not a postive integer "            retrun;        for i in range(1,n,3):            print i;        else:            print "loop output over ... ";    def __test(self):# 私人函數(函數首部帶有雙下劃綫)        print "類的私人函數,不能被類的執行個體直接調用,只能被專有函數調用(需要帶self關鍵字)";    def __my__(self):# 專有函數(函數名首尾帶有雙底線)        self.__test();        def dev__(self,a,b):        """示範異常"""        try:            return a/b;        except Exception,e:            print e.message;    def __passTest__(seLf):        """函數邏輯暫未規劃好時,採用pass關鍵字進行處理"""        pass;# 子類執行個體化b=m();# 調用子類方法print b.sub(100, 55); b.loopOutputFun(10);b.__my__();print b.dev__(10,2);b.__passTest__();

 

3、

 

python2學習------基礎文法2(類、類的繼承、類成員函數、防禦式編程)

聯繫我們

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