Python入門——類與對象:封裝、繼承、多態、類的組合


以下內容來自於網課學習筆記。

使用的環境:

  • Window10+64位操作系統
  • PyCharm+Python3.7

一、類與對象

class Ball:
    def setName(self,name):
        self.name=name

    def kick(self):
        print("我叫%s" %self.name)

a=Ball()
a.setName("A")

b=Ball()
b.setName("B")

a.kick()
b.kick()

結果:

我叫A
我叫B

二、__init__構造

  • init(self,param1)
    class Ball:
        def __init__(self,name):
            self.name = name
        
        def kick(self):
            print("我叫%s" % self.name)
    
    
    a = Ball('tt')
    a.kick()
    
    結果:
    我叫tt
    
  • init(self,param1,param2…)
    class Ball:
        def __init__(self, name):
            self.name = name
    
        def __init__(self, name, name2, name3):
            self.name = name
            self.name2 = name2
            self.name3 = name3
    
        def kick(self):
            print("%s" % self.name)
            print("%s" % self.name2)
            print("%s" % self.name3)
    
    
    a = Ball('tt', "rr", "ww")
    a.kick()
    

三、封裝

公有,私有
在Python中定義私有變量只需要在變量名數名前加上兩個下劃線“_”,那麼這個函數或變量就會爲私有的了。

class WaitFoF:
    name1="WW"
    __name="TT"
    def getPrivateName(self):
        print(self.__name)

w=WaitFoF()
print(w.name1)
print(w.__name)
w.getPrivateName()

結果:
對象訪問私有變量時出錯。
但在類內使用是正確的。

四、繼承

1. 單繼承

class Parent:
    def hello(self):
        print("正在調用父類的方法...")

# 括號內的類爲父類
class Child(Parent):
    pass

p=Parent()
p.hello()
c=Child()
c.hello()

2. 多繼承

class Base1:
    def foo1(self):
        print("正在調用Base1······")

class Base2:
    def foo2(self):
        print("正在調用Base2······")

class C(Base1,Base2):
    pass

c=C()
c.foo1()
c.foo2()

五、多態

如果子類中定義與父類同名的方法或屬性,則會自動覆蓋父類對應的方法或屬性。

class Parent:
    def hello(self):
        print("正在調用父類的方法...")

# 括號內的類爲父類
class Child(Parent):
    def hello(self):
        print("正在調用子類的方法...")

p=Parent()
p.hello()
c=Child()
c.hello()

六、組合

將幾個沒有縱向繼承關係的類組合到一起。

# 烏龜類
class Turtle:
    def __init__(self,x):
        self.num=x
# 魚類
class Fish:
    def __init__(self, x):
        self.num=x

# 水池類
# 烏龜和魚類都組合在水池類中
class Pool:
    def __init__(self, x, y):
        #turtle是一個Turtle對象
        #fish是一個Fish對象
        self.turtle = Turtle(x)
        self.fish = Fish(y)

    def print_num(self):
        print("水池中有烏龜 %d只,小魚%d條"%(self.turtle.num,self.fish.num))

pool=Pool(30,10)
pool.print_num()

結果:
水池中有烏龜 30只,小魚10條

七、子類中使用父類方法的方式

📢📢 調用未綁定的父類方法
📢📢 使用super函數

import  random as r
class Fish:
    # 初始座標
    def __init__(self):
        # 0~10之間
        self.x=r.randint(0,10)
        self.y=r.randint(0,10)

    # 一路向西遊
    def move(self):
        self.x-=1
        print("Fish: ["+str(self.x)+","+str(self.y)+"]")

class Goldfish(Fish):
    pass


class Shark(Fish):
    def __init__(self):
        self.hungry=True

    def eat(self):
        if self.hungry==True:
            print("Shark: is wait for eating")
            self.hungry=False
        else:
            print("Shark: is not hungry")

print("Fish:")
fish=Fish()
fish.move()
fish.move()
fish.move()

print("Goldfish:")
goldfish=Goldfish()
goldfish.move()
goldfish.move()

print("Shark:")
shark=Shark()
shark.eat()
shark.eat()
shark.move()

由於Shark類重載了init方法,會覆蓋父類的方法,因此Shark類中不存在x。

在子類中使用父類方法的方式:

  • 調用未綁定的父類方法

    class Shark(Fish):
        def __init__(self):
            # 調用未綁定的父類方法
            Fish.__init__(self)
            self.hungry=True
    
        def eat(self):
            if self.hungry==True:
                print("Shark: is wait for eating")
                self.hungry=False
            else:
                print("Shark: is not hungry")
    
    
    print("Fish:")
    fish=Fish()
    fish.move()
    fish.move()
    fish.move()
    
    print("Goldfish:")
    goldfish=Goldfish()
    goldfish.move()
    goldfish.move()
    
    print("Shark:")
    shark=Shark()
    shark.eat()
    shark.eat()
    shark.move()
    
    
  • 使用super函數

    import  random as r
    class Fish:
        # 初始座標
        def __init__(self):
            # 0~10之間
            self.x=r.randint(0,10)
            self.y=r.randint(0,10)
    
        # 一路向西遊
        def move(self):
            self.x-=1
            print("Fish: ["+str(self.x)+","+str(self.y)+"]")
    
    class Goldfish(Fish):
        pass
    
    class Garp(Fish):
        pass
    
    class Salmon(Fish):
        pass
    
    class Shark(Fish):
        def __init__(self):
            # 使用super方法
            super().__init__()
            self.hungry=True
    
        def eat(self):
            if self.hungry==True:
                print("Shark: is wait for eating")
                self.hungry=False
            else:
                print("Shark: is not hungry")
    
    
    print("Fish:")
    fish=Fish()
    fish.move()
    fish.move()
    fish.move()
    
    print("Goldfish:")
    goldfish=Goldfish()
    goldfish.move()
    goldfish.move()
    
    print("Shark:")
    shark=Shark()
    shark.eat()
    shark.eat()
    shark.move()
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章