亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Python中關(guān)鍵字Class的定義和使用方法

 更新時(shí)間:2025年07月03日 11:37:38   作者:ぃ曦曄°  
在Python中class是用來(lái)定義類(lèi)的關(guān)鍵字,通過(guò)class關(guān)鍵字可以創(chuàng)建一個(gè)新的類(lèi),該類(lèi)可以包含屬性和方法,這篇文章主要介紹了Python中關(guān)鍵字Class的定義和使用的相關(guān)資料,需要的朋友可以參考下

類(lèi)的定義

在 Python 中,class 是用來(lái)定義類(lèi)的關(guān)鍵字。通過(guò) class 關(guān)鍵字可以創(chuàng)建一個(gè)新的類(lèi),該類(lèi)可以包含屬性和方法。類(lèi)名通常使用大寫(xiě)字母開(kāi)頭的駝峰命名法。

  • 定義類(lèi)的基本語(yǔ)法:

    class 類(lèi)名:  # 類(lèi)名慣用駝峰式命名
        # 類(lèi)屬性(所有實(shí)例共享)
        類(lèi)屬性 = 值
    
        # 構(gòu)造方法(初始化對(duì)象)
        def __init__(self, 參數(shù)1, 參數(shù)2, ...):
            # 實(shí)例屬性(每個(gè)實(shí)例獨(dú)有)
            self.屬性1 = 參數(shù)1
            self.屬性2 = 參數(shù)2
    
        # 實(shí)例方法
        def 方法名(self, 參數(shù)1, 參數(shù)2, ...):
            # 方法體
            pass
    
        # 類(lèi)方法(使用 @classmethod 裝飾器)
        @classmethod
        def 類(lèi)方法名(cls, 參數(shù)1, 參數(shù)2, ...):
            # 方法體
            pass
    
        # 靜態(tài)方法(使用 @staticmethod 裝飾器)
        @staticmethod
        def 靜態(tài)方法名(參數(shù)1, 參數(shù)2, ...):
            # 方法體
            pass
    
  • 初始化方法 (__init__)
    當(dāng)定義一個(gè)類(lèi)時(shí),通常會(huì)提供一個(gè)特殊的方法 __init__() 來(lái)初始化新創(chuàng)建的對(duì)象的狀態(tài)。這個(gè)方法會(huì)在每次實(shí)例化對(duì)象時(shí)自動(dòng)調(diào)用。
    示例代碼如下:

    class Student:
    	# 初始化方法(構(gòu)造函數(shù))
        def __init__(self, id, name, course):
            self.id = id	 	  # 實(shí)例屬性
            self.name = name 	  # 實(shí)例屬性
            self.course = course  # 實(shí)例屬性
        # 實(shí)例方法
        def show_data(self):
            print(f"ID:\t{self.id}")
            print(f"Name:\t{self.name}")
            print(f"Course:\t{self.course}")
    
    # 實(shí)例化對(duì)象并調(diào)用方法
    student_obj = Student(1, 'Alice', 'Mathematics')
    student_obj.show_data()
    

    輸出結(jié)果為:
    ID:    1
    Name:    Alice
    Course:    Mathematics?

繼承與多態(tài)

繼承是面向?qū)ο缶幊痰闹匾匦?,它允許一個(gè)類(lèi)繼承另一個(gè)類(lèi)的屬性和方法。被繼承的類(lèi)稱(chēng)為基類(lèi)(父類(lèi)),繼承的類(lèi)稱(chēng)為派生類(lèi)(子類(lèi))

子類(lèi)可以通過(guò) super() 函數(shù)來(lái)調(diào)用父類(lèi)的構(gòu)造函數(shù)或其他方法。

類(lèi)的繼承

下面是一個(gè)簡(jiǎn)單的繼承例子:

class ParentClass:
    def __init__(self, value):
        self.value = value

    def display_value(self):
        print(f"Value in parent class: {self.value}")

class ChildClass(ParentClass):
    def __init__(self, value, extra_value):
        super().__init__(value)
        self.extra_value = extra_value

    def display_extra_value(self):
        print(f"Extra Value in child class: {self.extra_value}")

child_instance = ChildClass(10, 20)
child_instance.display_value()       # 調(diào)用了父類(lèi)的方法
child_instance.display_extra_value() # 調(diào)用了子類(lèi)自己的方法

運(yùn)行以上代碼的結(jié)果將是:

Value in parent class: 10
Extra Value in child class: 20

方法重寫(xiě)

子類(lèi)可以重寫(xiě)父類(lèi)的方法,以實(shí)現(xiàn)不同的行為。

# 父類(lèi)
class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return f"{self.name} makes a sound."

# 子類(lèi)    繼承于父類(lèi)animal
class Cat(Animal):
    def speak(self):
        return f"{self.name} says meow!"
        
# 子類(lèi)  重寫(xiě)父類(lèi)的speak方法
class Bird(Animal):
    def speak(self):
        return f"{self.name} says chirp!"

# 創(chuàng)建子類(lèi)對(duì)象
my_cat = Cat("Whiskers")
print(my_cat.speak())  # 輸出: Whiskers says meow!

my_bird = Bird("Tweety")
print(my_bird.speak())  # 輸出: Tweety says chirp!

多繼承

Python 支持多繼承,即一個(gè)類(lèi)可以繼承多個(gè)父類(lèi)。

class A:
    def method(self):
        return "A"

class B:
    def method(self):
        return "B"

class C(A, B):
    pass

my_object = C()
print(my_object.method())  # 輸出: A(遵循方法解析順序 MRO)

靜態(tài)方法和類(lèi)方法

靜態(tài)方法使用 @staticmethod 裝飾器定義,類(lèi)方法使用 @classmethod 裝飾器定義。

class MyClass:
    @staticmethod
    def static_method():
        print("This is a static method.")
 
    @classmethod
    def class_method(cls):
        print("This is a class method.")
 
MyClass.static_method()  # 輸出: This is a static method.
MyClass.class_method()   # 輸出: This is a class method.
  • 靜態(tài)方法
    裝飾有@staticmethod標(biāo)志的方法被視作靜態(tài)方法,既不需要傳入self也不需傳遞cls作為默認(rèn)參數(shù)。這類(lèi)方法實(shí)際上更接近于普通的全局輔助工具型函數(shù),在語(yǔ)法結(jié)構(gòu)上只是掛載到了某特定類(lèi)之下而已。

  • 類(lèi)方法
    使用裝飾器@classmethod標(biāo)記的方法被稱(chēng)為類(lèi)方法,它的首個(gè)隱含參數(shù)通常是代表類(lèi)本身的cls而非具體實(shí)例。因此,此類(lèi)方法適用于那些需要處理整個(gè)類(lèi)范圍內(nèi)的事務(wù)場(chǎng)景下。

    class Example:
        count = 0  # 類(lèi)屬性
        
        def __init__(self, value):
            self.value = value  # 實(shí)例屬性
            
        @classmethod
        def increment_count(cls):
            cls.count += 1  # 修改類(lèi)屬性
          
        @staticmethod
        def static_method():
            print("This is a static method.")
            
        def instance_method(self):
            return f"Value: {self.value}"  # 訪(fǎng)問(wèn)實(shí)例屬性
    

類(lèi)的特殊方法

Python 中還存在一系列內(nèi)置的特殊命名方法(即魔術(shù)方法),允許開(kāi)發(fā)者自定義某些標(biāo)準(zhǔn)運(yùn)算符或者語(yǔ)句的表現(xiàn)形式。

它們以雙下劃線(xiàn)開(kāi)頭和結(jié)尾,例如 __str__()__repr__(), 和容器相關(guān)的 __len__()__getitem__() 等等。合理運(yùn)用這些魔法方法可以讓我們的類(lèi)更加 Pythonic 并且易于與其他組件集成工作。

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    # 重寫(xiě)字符串表示
    def __str__(self):
        return f"Point({self.x}, {self.y})"

    # 重寫(xiě)加法操作
    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)

# 使用
p1 = Point(1, 2)
p2 = Point(3, 4)
print(p1)          # 輸出: Point(1, 2)
print(p1 + p2)     # 輸出: Point(4, 6)

類(lèi)的封裝

  • 封裝的意義
    封裝是一種面向?qū)ο缶幊痰暮诵奶匦灾唬试S將數(shù)據(jù)(屬性)和操作這些數(shù)據(jù)的方法組合在一起,并對(duì)外部隱藏不必要的細(xì)節(jié)。通過(guò)封裝,可以提高程序的安全性和可維護(hù)性。

在 Python 中,可以通過(guò)命名約定來(lái)定義不同級(jí)別的訪(fǎng)問(wèn)權(quán)限:

  • 公有屬性 (Public)

    公有屬性可以直接被外部訪(fǎng)問(wèn)和修改。

  • 受保護(hù)屬性 (Protected)

    受保護(hù)屬性以單下劃線(xiàn) _ 開(kāi)頭,表示該屬性?xún)H應(yīng)在類(lèi)內(nèi)部或其子類(lèi)中使用。雖然可以從外部訪(fǎng)問(wèn),但這通常被視為一種慣例。

  • 私有屬性 (Private)

    私有屬性以雙下劃線(xiàn) __ 開(kāi)頭,Python 會(huì)對(duì)這類(lèi)屬性進(jìn)行名稱(chēng)改寫(xiě)(Name Mangling),從而防止從外部直接訪(fǎng)問(wèn)。

class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner                # 公有屬性
        self._account_number = "A12345" # 受保護(hù)屬性
        self.__balance = balance         # 私有屬性
    
    def deposit(self, amount):
        """存款"""
        if amount > 0:
            self.__balance += amount
            return f"Deposited {amount}. New balance: {self.__balance}"
        else:
            return "Invalid deposit amount."
    
    def withdraw(self, amount):
        """取款"""
        if 0 < amount <= self.__balance:
            self.__balance -= amount
            return f"Withdrew {amount}. Remaining balance: {self.__balance}"
        else:
            return "Insufficient funds or invalid withdrawal amount."
    
    def get_balance(self):
        """獲取余額"""
        return f"Current balance: {self.__balance}"

# 測(cè)試BankAccount類(lèi)的功能
account = BankAccount("Alice", 100)

# 正常操作
print(account.deposit(50))          # 輸出: Deposited 50. New balance: 150
print(account.withdraw(70))         # 輸出: Withdrew 70. Remaining balance: 80
print(account.get_balance())        # 輸出: Current balance: 80

# 嘗試非法訪(fǎng)問(wèn)私有屬性
try:
    print(account.__balance)       # 這里會(huì)拋出 AttributeError 錯(cuò)誤
except AttributeError as e:
    print(e)                       # 輸出: 'BankAccount' object has no attribute '__balance'

# 使用名稱(chēng)改寫(xiě)的機(jī)制間接訪(fǎng)問(wèn)私有屬性
print(account._BankAccount__balance)  # 輸出: 80 【不推薦】

單例模式下的封裝應(yīng)用除了基本的數(shù)據(jù)封裝外,在某些場(chǎng)景下可能還需要確保某個(gè)類(lèi)只存在一個(gè)實(shí)例。這種需求可以通過(guò)重寫(xiě) __new__ 方法并結(jié)合靜態(tài)變量實(shí)現(xiàn)單例模式。

以下是基于日志管理器的一個(gè)簡(jiǎn)單示例:

class Logger:
    _instance = None                 # 靜態(tài)變量用于存儲(chǔ)唯一實(shí)例
    
    def __new__(cls, *args, **kwargs):
        if not cls._instance:        # 如果尚未創(chuàng)建過(guò)實(shí)例,則初始化一個(gè)新的實(shí)例
            cls._instance = super(Logger, cls).__new__(cls)
        return cls._instance         # 返回已存在的實(shí)例
    
    def log(self, message):
        print(f"[LOG]: {message}")

# 測(cè)試Logger類(lèi)的行為
logger1 = Logger()
logger2 = Logger()

assert logger1 is logger2           # True,表明兩個(gè)引用指向同一個(gè)對(duì)象
logger1.log("System started.")      # 輸出: [LOG]: System started.
logger2.log("User logged in.")     # 輸出: [LOG]: User logged in.

總結(jié)以上兩段代碼分別演示了常規(guī)封裝技術(shù)和單例設(shè)計(jì)模式中的封裝實(shí)踐。前者強(qiáng)調(diào)的是對(duì)敏感字段的有效隔離;后者則進(jìn)一步擴(kuò)展到整個(gè)類(lèi)層面,保證資源使用的統(tǒng)一性。

總結(jié)

到此這篇關(guān)于Python中關(guān)鍵字Class的定義和使用方法的文章就介紹到這了,更多相關(guān)Python  Class使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論