# 繼承# 類定義classpeople:# 定義基本屬性
name =''
age =0# 定義私有屬性,私有屬性在類外部無法直接進行訪問
__weight =0# 定義構造方法def__init__(self, n, a, w):
self.name = n
self.age = a
self.__weight = w
defspeak(self):print("%s 說: 我 %d 歲。"%(self.name, self.age))# 單繼承示例classstudent(people):
grade =''def__init__(self, n, a, w, g):# 調用父類的構函
people.__init__(self, n, a, w)
self.grade = g
# 覆寫父類的方法defspeak(self):print("%s 說: 我 %d 歲了,我在讀 %d 年級"%(self.name, self.age, self.grade))
s = student('ken',10,60,3)
s.speak()# 另一個類,多重繼承之前的準備classspeaker():
topic =''
name =''def__init__(self, n, t):
self.name = n
self.topic = t
defspeak(self):print("我叫 %s,我是一個演說家,我演講的主題是 %s"%(self.name, self.topic))# 需要注意圓括號中父類的順序,若是父類中有相同的方法名,而在子類使用時未指定,python從左至右搜索 即方法在子類中未找到時,從左到右查找父類中是否包含方法classsample(speaker, student):
a =''def__init__(self, n, a, w, g, t):
student.__init__(self, n, a, w, g)
speaker.__init__(self, n, t)
test = sample("Tim",25,80,4,"Python")
test.speak()# 方法名同,默認調用的是在括號中排前地父類的方法# 方法重寫classParent:# 定義父類defmyMethod(self):print('調用父類方法')classChild(Parent):# 定義子類defmyMethod(self):print('調用子類方法')
c = Child()# 子類實例
c.myMethod()# 子類調用重寫方法super(Child, c).myMethod()# 用子類對象調用父類已被覆蓋的方法#運算符重載classVector:def__init__(self, a, b):
self.a = a
self.b = b
def__str__(self):return'Vector (%d, %d)'%(self.a, self.b)def__add__(self, other):return Vector(self.a + other.a, self.b + other.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)print(v1 + v2)#全局變量和局部變量
total =0# 這是一個全局變量# 可寫函數說明defsum(arg1, arg2):# 返回2個參數的和."
total = arg1 + arg2 # total在這裏是局部變量.print("函數內是局部變量 : ", total)return total
# 調用sum函數sum(10,20)print("函數外是全局變量 : ", total)# global 和 nonlocal關鍵字# 內部作用域想修改外部作用域的變量
num =1deffun1():global num # 需要使用 global 關鍵字聲明print(num)
num =123print(num)
fun1()print(num)defouter():
num =10definner():nonlocal num # nonlocal關鍵字聲明
num =100print(num)
inner()print(num)
outer()