Python學習筆記2:類的定義和繼承
來源:程序員人生 發布時間:2014-10-04 08:00:00 閱讀次數:3294次
# 類的定義
格式:
class 類名(父類):
__init(self,參數)
成員方法
成員變量
# 所有類的基礎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): # 構造函數
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): # 構造函數
self.gender = gender # 定義并初始化公有屬性
def __show_laugh(self): # 私有方法
print self.laugh
def show_laugh_twice(self): # 公有方法
self.show_laugh() # 調用私有方法
self.show_laugh() # 調用私有方法
使用:
man = Human("male")
man.show_laugh_twice()
print man.gender
附錄:
# 內置函數
# dir() 用來查詢一個類或對象的屬性
# help()用來查閱說明文檔
# 序列常用函數
len(s)-元素個數
min(s)-最小的元素
max(s)-最大的元素
sum(s)-求和
s.count(x)-元素x在序列s中的出現次數
s.index(x)-元素x在序列s中第一次出現的下標
# 表(由于定值表的元素師不可變更的)
l.extend(l2)-在表l后添加l2的全部元素
l.append(x)-在l的末尾附加x元素
l.sort()-對l中的元素排序
l.reverse()-將l中的元素逆序
l.pop()-返回:表l的最后一個元素,并在表l中刪除該元素
del l[i]-刪除該元素
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈