天天看點

【Python】類與對象類的建立對象的建立類屬性、類方法、靜态變量動态綁定屬性和方法總結

本文為 Python 學習筆記,講解類與對象。歡迎在評論區與我交流👏

文章目錄

  • 類的建立
    • 文法
    • 類的組成
  • 對象的建立
  • 類屬性、類方法、靜态變量
    • 類屬性
    • 類方法
    • 靜态方法
  • 動态綁定屬性和方法
    • 動态綁定屬性
    • 動态綁定方法
  • 總結

類的建立

文法

class Student:
    pass
           

Python 中一切皆對象:

【Python】類與對象類的建立對象的建立類屬性、類方法、靜态變量動态綁定屬性和方法總結

此處的

Student

為一個類對象:

class Student:
    pass

print(id(Student))
print(type(Student))
print(Student)
           

輸出結果:

【Python】類與對象類的建立對象的建立類屬性、類方法、靜态變量動态綁定屬性和方法總結

類的組成

【Python】類與對象類的建立對象的建立類屬性、類方法、靜态變量動态綁定屬性和方法總結
class Student:
    native_place='吉林' # 類屬性
    def __init__(self, name, age):
        self.name=name # 執行個體屬性
        self.age=age
    # 執行個體方法
    def eat(self):
        print('學生在吃飯。。。')

    # 靜态方法
    @staticmethod
    def method():
        print('使用 staticmethod 修飾,是靜态方法')

    # 類方法
    @classmethod
    def cm(cls):
        print('類方法,使用 classmethod 修飾')
           
  • 初始化方法

    __init__

    ,此處将局部變量的值賦給實體屬性
  • 執行個體方法與函數相似,但必須包含

    self

    參數
  • 靜态方法中不能寫

    self

  • 類方法要傳入

    cls

    ,表示 class

對象的建立

stu1=Student('張三', 20)
stu1.eat()
print(stu1.name)
print(stu1.age)

Student.eat(stu1) # 與第 2 行等價,實際上就是方法處的 self
           

輸出結果:

【Python】類與對象類的建立對象的建立類屬性、類方法、靜态變量動态綁定屬性和方法總結

類屬性、類方法、靜态變量

類屬性

類中方法外的變量,被所有對象共享:

stu1=Student('張三', 20)
stu2=Student('李四', 30)
print(stu1.native_place)
print(stu2.native_place)
Student.native_place='天津'
print(stu1.native_place)
print(stu2.native_place)
           

記憶體示意圖:

【Python】類與對象類的建立對象的建立類屬性、類方法、靜态變量動态綁定屬性和方法總結

類方法

使用類名直接通路的方法:

靜态方法

靜态方法無預設參數,使用類名直接通路的方法:

動态綁定屬性和方法

【Python】類與對象類的建立對象的建立類屬性、類方法、靜态變量動态綁定屬性和方法總結

動态綁定屬性

記憶體示意圖:

【Python】類與對象類的建立對象的建立類屬性、類方法、靜态變量動态綁定屬性和方法總結

demo:

stu1=Student('張三', 20)
stu2=Student('李四', 30)
print(id(stu1))
print(id(stu2))
print('--------為 stu2 動态綁定性别屬性--------')
stu1.gender='女'
print(stu1.name, stu1.age, stu1.gender)
print(stu2.name, stu2.age)
# print(stu2.name, stu2.age, stu2.gender) # 報錯
           

輸出結果:

【Python】類與對象類的建立對象的建立類屬性、類方法、靜态變量動态綁定屬性和方法總結

動态綁定方法

def show():
    print('定義在類之外,為函數')
stu1.show=show
stu1.show()
# stu2.show() # 報錯
           

總結

【Python】類與對象類的建立對象的建立類屬性、類方法、靜态變量動态綁定屬性和方法總結

有用的話點個贊加關注吧 😉