python基礎練習(四)

代碼

# 繼承
# 類定義
class people:
    # 定義基本屬性
    name = ''
    age = 0
    # 定義私有屬性,私有屬性在類外部無法直接進行訪問
    __weight = 0

    # 定義構造方法
    def __init__(self, n, a, w):
        self.name = n
        self.age = a
        self.__weight = w

    def speak(self):
        print("%s 說: 我 %d 歲。" % (self.name, self.age))


# 單繼承示例
class student(people):
    grade = ''

    def __init__(self, n, a, w, g):
        # 調用父類的構函
        people.__init__(self, n, a, w)
        self.grade = g

    # 覆寫父類的方法
    def speak(self):
        print("%s 說: 我 %d 歲了,我在讀 %d 年級" % (self.name, self.age, self.grade))


s = student('ken', 10, 60, 3)
s.speak()


# 另一個類,多重繼承之前的準備
class speaker():
    topic = ''
    name = ''

    def __init__(self, n, t):
        self.name = n
        self.topic = t

    def speak(self):
        print("我叫 %s,我是一個演說家,我演講的主題是 %s" % (self.name, self.topic))


# 需要注意圓括號中父類的順序,若是父類中有相同的方法名,而在子類使用時未指定,python從左至右搜索 即方法在子類中未找到時,從左到右查找父類中是否包含方法
class sample(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()  # 方法名同,默認調用的是在括號中排前地父類的方法

# 方法重寫
class Parent:  # 定義父類
    def myMethod(self):
        print('調用父類方法')


class Child(Parent):  # 定義子類
    def myMethod(self):
        print('調用子類方法')


c = Child()  # 子類實例
c.myMethod()  # 子類調用重寫方法
super(Child, c).myMethod()  # 用子類對象調用父類已被覆蓋的方法

#運算符重載
class Vector:
    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  # 這是一個全局變量
# 可寫函數說明
def sum(arg1, arg2):
    # 返回2個參數的和."
    total = arg1 + arg2  # total在這裏是局部變量.
    print("函數內是局部變量 : ", total)
    return total
# 調用sum函數
sum(10, 20)
print("函數外是全局變量 : ", total)


# global 和 nonlocal關鍵字
# 內部作用域想修改外部作用域的變量
num = 1
def fun1():
    global num  # 需要使用 global 關鍵字聲明
    print(num)
    num = 123
    print(num)
fun1()
print(num)

def outer():
    num = 10
    def inner():
        nonlocal num   # nonlocal關鍵字聲明
        num = 100
        print(num)
    inner()
    print(num)
outer()


結果

ken 說:10 歲了,我在讀 3 年級
我叫 Tim,我是一個演說家,我演講的主題是 Python
調用子類方法
調用父類方法
Vector (7, 8)
函數內是局部變量 :  30
函數外是全局變量 :  0
1
123
123
100
100
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章