Python學(xué)習(xí)筆記2:類的定義和繼承
來源:程序員人生 發(fā)布時間:2014-10-04 08:00:00 閱讀次數(shù):3302次
# 類的定義
格式:
class 類名(父類):
__init(self,參數(shù))
成員方法
成員變量
# 所有類的基礎(chǔ)object
# 私有方法和變量使用__開頭
例如:定義一個鳥類
class Bird(object):
__have_feather = True # 私有屬性:是否有羽毛
way_of_reproduct = "egg" # 公有屬性:繁殖方式
def move(self, dx, dy): # 公有方法
position = [0,0]
position[0] = position[0] + dx
position[1] = position[1] + dy
return position
定義一個雞類:繼承自鳥類
class Chicken(Bird):
way_of_move = "walk" # 添加一個公有屬性
定義一個海鷗類:繼承自鳥類
class Oriole(Bird):
way_of_move = "fly" # 添加一個公有屬性
定義一個幸福鳥類:繼承自鳥類
class happyBird(Bird):
def __init(self, words): # 構(gòu)造函數(shù)
print "We are happy birds,", words
使用:
summer = Bird()
print "after move:",summer.move(5,8)
happy = happyBird()
例:定義一個人類
class Human(object):
laugh = "hahaha" # 公有屬性
def __init__(self, gender): # 構(gòu)造函數(shù)
self.gender = gender # 定義并初始化公有屬性
def __show_laugh(self): # 私有方法
print self.laugh
def show_laugh_twice(self): # 公有方法
self.show_laugh() # 調(diào)用私有方法
self.show_laugh() # 調(diào)用私有方法
使用:
man = Human("male")
man.show_laugh_twice()
print man.gender
附錄:
# 內(nèi)置函數(shù)
# dir() 用來查詢一個類或?qū)ο蟮膶傩?br>
# help()用來查閱說明文檔
# 序列常用函數(shù)
len(s)-元素個數(shù)
min(s)-最小的元素
max(s)-最大的元素
sum(s)-求和
s.count(x)-元素x在序列s中的出現(xiàn)次數(shù)
s.index(x)-元素x在序列s中第一次出現(xiàn)的下標(biāo)
# 表(由于定值表的元素師不可變更的)
l.extend(l2)-在表l后添加l2的全部元素
l.append(x)-在l的末尾附加x元素
l.sort()-對l中的元素排序
l.reverse()-將l中的元素逆序
l.pop()-返回:表l的最后一個元素,并在表l中刪除該元素
del l[i]-刪除該元素
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學(xué)習(xí)有所幫助,可以手機掃描二維碼進(jìn)行捐贈