python的類機制

python的類機制

參考:python面向對象

概念

  1. 方法重寫/覆蓋:若從父類繼承的方法不能滿足子類的需求,可以對其進行改寫。
  2. 類變量:在實例化對象中是公用的,定義在類中,且在函數體之外,通常不作爲實體變量使用。
  3. 局部變量:定義在方法中的變量,只作用在當前實例。
  4. 實例變量:在類的聲明中,屬性是用變量表示的,用self修飾。
  5. 繼承關係:派生對象”是一個“繼承對象,例如Dog是一個Animal。
  6. 對象:通過類定義的數據結構實例,包含類變量、實例變量和方法。

類屬性

  1. 私有屬性

兩個下劃線開頭,聲明該屬性爲私有,不能在類的外部被使用或直接訪問。例如:__private_attrs,在類內部的方法中使用時 self.__private_attrs

  1. 私有方法

兩個下劃線開頭,聲明該方法爲私有方法,只能在類的內部調用 ,不能在類的外部調用。例如:__private_methods,使用方法:self.__private_methods。

#!/usr/bin/python3
 
class JustCounter:
    __secretCount = 0  # 私有變量
    publicCount = 0    # 公開變量
 
    def count(self):
        self.__secretCount += 1
        self.publicCount += 1
        print (self.__secretCount)
 
counter = JustCounter()
counter.count()
counter.count()
print (counter.publicCount)
print (counter.__secretCount)  # 報錯,實例不能訪問私有變量

專有方法

image-20240219223255800

類對象

支持2種操作:

  1. 屬性引用:對象.屬性
  2. 實例化
class MyClass:
    """一個簡單的類實例"""
    i = 12345
    def f(self):
        return 'hello world'
 
# 實例化類
x = MyClass()
 
# 訪問類的屬性和方法
print("MyClass 類的屬性 i 爲:", x.i)
print("MyClass 類的方法 f 輸出爲:", x.f())
# 輸出
MyClass 類的屬性 i 爲: 12345
MyClass 類的方法 f 輸出爲: hello world

構造方法:

類中有一個__init__() 方法,在類實例化時(x = MyClass())會自動調用:

def __init__(self):
    self.data = []

和java一樣,當沒有定義的時候,會自動生成,也可以有參數,進而能傳遞到類的實例化操作上:

class Complex:
    def __init__(self, realpart, imagpart):
        self.r = realpart
        self.i = imagpart
x = Complex(3.0, -4.5)
print(x.r, x.i)   
# 輸出
3.0 -4.5

類方法:

類方法不同於普通函數之處:必須有一個額外的第一個參數名稱,通常爲self或者this,也可以是任意詞。

class Test:
    def prt(self):
        print(self)
        print(self.__class__)
 
t = Test()
t.prt()
# 輸出
<__main__.Test instance at 0x100771878>
__main__.Test
  • self代表的是類的實例,表示當前對象的地址,self.class表示類。
#類定義
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 歲,%d kg。" %(self.name,self.age,self.__weight))

# 實例化類
p = people('runoob',10,30)
p.speak()
# 輸出
runoob 說: 我 10 歲,30 kg。

繼承

子類(派生類 DerivedClassName)會繼承父類(基類 BaseClassName)的屬性和方法。

單繼承

#類定義
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()
# 輸出
ken 說: 我 10 歲了,我在讀 3 年級

多繼承

若父類中有相同方法名,在子類使用時未指定,則從左到右查找父類中是是否包含該方法。

#類定義
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))

#另一個類,多繼承之前的準備
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))

#多繼承
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()   #方法名同,默認調用的是在括號中參數位置排前父類的方法
# 輸出
我叫 Tim,我是一個演說家,我演講的主題是 Python

方法重寫

super() 函數是用於調用父類(超類)的一個方法。

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

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

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

參考:Python 子類繼承父類構造函數說明

運算符重載

__str__ 是一個類的方法,在打印類對象,獲取其屬性信息時調用。打印一個實例化對象時,默認打印的其實時一個對象的地址但是我們可以對其進行重載,打印我們想要的信息

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)
# 輸出
Vector (7, 8)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章