標籤: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的類 介紹