码迷,mamicode.com
首页 > 编程语言 > 详细

面向对象 Python的类 介绍

时间:2016-12-23 02:15:14      阅读:136      评论:0      收藏:0      [点我收藏+]

标签: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 class
print x.name

print "Kate\‘s number is 1235678."

print "It\‘s square root are:"
print x.sqrt_num(1235678)  # invoke the function sqrt_num

print "Kate\‘s string is agahccp."
print "It\‘s count is:"
print x.c_str("agahccp")   # invoke the function c_str

for i in Test_N.square_list(3,4,5,6,7):   # invoke the method squre_list
    print i

print x.anno_genome("log.txt")    # invoke the function anno_genome


输出结果如下

Kate
Kate‘s number is 1235678.
It‘s square root are:
(-1111.6105433109205, 1111.6105433109205)
Kate‘s string is agahccp.
It‘s count is:
7
9
16
25
36
49
36


其中log.txt 是一个有36行的文件,所以输出的最后一个数字是36

面向对象 Python的类 介绍

标签:python class 类 静态方法

原文地址:http://matrix6ro.blog.51cto.com/1746429/1885258

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!