物件導向 Python的類 介紹

來源:互聯網
上載者:User

標籤:python class 類 靜態方法

python中定義類的方法很簡單,用關鍵字class, 其中可以包含函數 用 def

#!/usr/bin/env python# -*- coding:UTF-8 -*-class Test_N:    """ class get a name and count string or number """    def __init__(self, n):        self.name = n    def sqrt_num(self, cn):        if cn >= 0:            root = cn ** 0.5            return -root, root        else:            print "negative number."            return    def c_str(self, cs):        return len(cs)    @staticmethod    def square_list( *args ):        r = []        for i in args:            r.append(i ** 2)        return r    def genome_len(self, fasta):        return len(fasta)    def anno_genome(self , gff):        handle = open(gff, ‘r‘)        n = 0        for i in handle:            n += 1        handle.close()        return n                        x = Test_N("Kate")      # initiate the classprint x.nameprint "Kate\‘s number is 1235678."print "It\‘s square root are:"print x.sqrt_num(1235678)  # invoke the function sqrt_numprint "Kate\‘s string is agahccp."print "It\‘s count is:"print x.c_str("agahccp")   # invoke the function c_strfor i in Test_N.square_list(3,4,5,6,7):   # invoke the method squre_list    print iprint x.anno_genome("log.txt")    # invoke the function anno_genome


輸出結果如下

KateKate‘s number is 1235678.It‘s square root are:(-1111.6105433109205, 1111.6105433109205)Kate‘s string is agahccp.It‘s count is:791625364936


其中log.txt 是一個有36行的檔案,所以輸出的最後一個數字是36

物件導向 Python的類 介紹

聯繫我們

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