Python学习笔记:类

类可以将数据与函数封装起来,用一个例子解释,先定义一个类:

1 class athlete:
2     def __init__(self,a_name,a_dob=None,a_times=[]):
3         self.name = a_name
4         self.dbo = a_dob
5         self.time = a_times

athlete是类的名字,self变量名,self后面的都是参数,而后面的代码就是将a_name这个参数的值赋给了self的name属性,以此类推。定义好了之后来试试:

1 sarah = athlete('sarah sweeney','2002-6-17',['2:58','2.58','1.56'])
2 sarah.time
3 ['2:58', '2.58', '1.56']
4 sarah.name
5 'sarah sweeney'

再修改一下这个类,让它的功能更强大:

1 class athlete:
2     def __init__(self,a_name,a_dob=None,a_times=[]):
3          self.name = a_name
4          self.dbo = a_dob
5          self.time = a_times
6     def top3(self):
7         return(sorted(set([sanitize(t) for t in self.time]))[0:3])

在类中定义函数,函数中可以直接引用类的属性值,即在7行直接引用了self.time。现在再来看看这个类的新功能:

1 >>> c_james=athlete('James Lee','2002-3-14',['2-01', '2-16', '2:22','2:30'])
2 >>> c_james.top3()
3 ['2.01', '2.16', '2.22']

总结的来说,类其实就是自己所定义的一种特殊的数据类型

Python还可以定义继承了内置类(比如说list,dict,set)的类,这种方法用我自己的话解释就是将自己想要的功能添加到Python原有的类上面,定义方式只要在类名称后面加上要继承的类:

1 def newlist(list):
2     def __init__(self,new_varible...):
3              ....

 

posted @ 2017-04-14 17:12  hahaxzy  阅读(221)  评论(0编辑  收藏  举报