您的位置:首页 > 编程语言 > Python开发

第六章 第二节

2016-04-09 16:41 447 查看
为什么要创建类?

1:有助于降低复杂度

2:复杂度减少意味着bug更少

3:相应的维护量同样也减少了

在面向对象的世界中,代码成为类的方法,数据称为类的属性,而实例化的数据(?)对象成为实例。

python 利用 class定义类

class Athelete:
def __init__(self)
...


没有self参数赋值,python解释器无法得出方法调用要应用到那个对象实例中去

class Athelete:
def __init__(self,value=0):
self.thing = value
def how_big(self):
return len(self.thing)


第3行中将提供的值赋至一个名为”self.thing”的类属性。

代码实例

`def sanitize(time_string):
if '-' in time_string:
splitter = '-'
elif ':' in time_string:
splitter = ':'
else:
return time_string
mins,secs = time_string.split(splitter)
return(mins+'.'+secs)

class Athlete:
def __init__(self,a_name,a_dob = None,a_times=[]):
self.name = a_name
self.dob = a_dob
self.times = a_times

def top3(self):
return sorted(set(sanitize(t) for t in self.times))[0:3]

def get_coach_data(file_name):
try:
with open(file_name) as f:
data = f.readline()
temp1 = data.strip().split(',')
return Athlete(temp1.pop(0),temp1.pop(0),temp1)

except IOError as ioerr:
print 'file error: '+ str(ioerr)
return None

james = get_coach_data('james2.txt')
print james.name + "'fastese times are: " + str(james.top3())`


因此只需要将应用到的新功能封装在类中,没有任何限制。

append(),extend()

`x = [1, 2, 3]
x.append([4, 5])
print (x)`


gives you: [1, 2, 3, [4, 5]]

`x = [1, 2, 3]
x.extend([4, 5])
print (x)`


gives you: [1, 2, 3, 4, 5]

一个添加对象,一个添加列表。

继承

多重继承
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 对象