Python中關(guān)鍵字Class的定義和使用方法
類的定義
在 Python 中,class
是用來定義類的關(guān)鍵字。通過 class
關(guān)鍵字可以創(chuàng)建一個新的類,該類可以包含屬性和方法。類名通常使用大寫字母開頭的駝峰命名法。
定義類的基本語法:
class 類名: # 類名慣用駝峰式命名 # 類屬性(所有實(shí)例共享) 類屬性 = 值 # 構(gòu)造方法(初始化對象) def __init__(self, 參數(shù)1, 參數(shù)2, ...): # 實(shí)例屬性(每個實(shí)例獨(dú)有) self.屬性1 = 參數(shù)1 self.屬性2 = 參數(shù)2 # 實(shí)例方法 def 方法名(self, 參數(shù)1, 參數(shù)2, ...): # 方法體 pass # 類方法(使用 @classmethod 裝飾器) @classmethod def 類方法名(cls, 參數(shù)1, 參數(shù)2, ...): # 方法體 pass # 靜態(tài)方法(使用 @staticmethod 裝飾器) @staticmethod def 靜態(tài)方法名(參數(shù)1, 參數(shù)2, ...): # 方法體 pass
初始化方法 (
__init__
)
當(dāng)定義一個類時,通常會提供一個特殊的方法__init__()
來初始化新創(chuàng)建的對象的狀態(tài)。這個方法會在每次實(shí)例化對象時自動調(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í)例化對象并調(diào)用方法 student_obj = Student(1, 'Alice', 'Mathematics') student_obj.show_data()
輸出結(jié)果為:
ID: 1
Name: Alice
Course: Mathematics?
繼承與多態(tài)
繼承是面向?qū)ο缶幊痰闹匾匦?,它允許一個類繼承另一個類的屬性和方法。被繼承的類稱為基類(父類),繼承的類稱為派生類(子類)
子類可以通過 super()
函數(shù)來調(diào)用父類的構(gòu)造函數(shù)或其他方法。
類的繼承
下面是一個簡單的繼承例子:
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)用了父類的方法 child_instance.display_extra_value() # 調(diào)用了子類自己的方法
運(yùn)行以上代碼的結(jié)果將是:
Value in parent class: 10
Extra Value in child class: 20
方法重寫
子類可以重寫父類的方法,以實(shí)現(xiàn)不同的行為。
# 父類 class Animal: def __init__(self, name): self.name = name def speak(self): return f"{self.name} makes a sound." # 子類 繼承于父類animal class Cat(Animal): def speak(self): return f"{self.name} says meow!" # 子類 重寫父類的speak方法 class Bird(Animal): def speak(self): return f"{self.name} says chirp!" # 創(chuàng)建子類對象 my_cat = Cat("Whiskers") print(my_cat.speak()) # 輸出: Whiskers says meow! my_bird = Bird("Tweety") print(my_bird.speak()) # 輸出: Tweety says chirp!
多繼承
Python 支持多繼承,即一個類可以繼承多個父類。
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)方法和類方法
靜態(tài)方法使用 @staticmethod 裝飾器定義,類方法使用 @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ù)。這類方法實(shí)際上更接近于普通的全局輔助工具型函數(shù),在語法結(jié)構(gòu)上只是掛載到了某特定類之下而已。類方法
使用裝飾器@classmethod
標(biāo)記的方法被稱為類方法,它的首個隱含參數(shù)通常是代表類本身的cls
而非具體實(shí)例。因此,此類方法適用于那些需要處理整個類范圍內(nèi)的事務(wù)場景下。class Example: count = 0 # 類屬性 def __init__(self, value): self.value = value # 實(shí)例屬性 @classmethod def increment_count(cls): cls.count += 1 # 修改類屬性 @staticmethod def static_method(): print("This is a static method.") def instance_method(self): return f"Value: {self.value}" # 訪問實(shí)例屬性
類的特殊方法
Python 中還存在一系列內(nèi)置的特殊命名方法(即魔術(shù)方法),允許開發(fā)者自定義某些標(biāo)準(zhǔn)運(yùn)算符或者語句的表現(xiàn)形式。
它們以雙下劃線開頭和結(jié)尾,例如 __str__()
, __repr__()
, 和容器相關(guān)的 __len__()
, __getitem__()
等等。合理運(yùn)用這些魔法方法可以讓我們的類更加 Pythonic 并且易于與其他組件集成工作。
class Point: def __init__(self, x, y): self.x = x self.y = y # 重寫字符串表示 def __str__(self): return f"Point({self.x}, {self.y})" # 重寫加法操作 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)
類的封裝
- 封裝的意義
封裝是一種面向?qū)ο缶幊痰暮诵奶匦灾?,它允許將數(shù)據(jù)(屬性)和操作這些數(shù)據(jù)的方法組合在一起,并對外部隱藏不必要的細(xì)節(jié)。通過封裝,可以提高程序的安全性和可維護(hù)性。
在 Python 中,可以通過命名約定來定義不同級別的訪問權(quán)限:
公有屬性 (Public)
公有屬性可以直接被外部訪問和修改。
受保護(hù)屬性 (Protected)
受保護(hù)屬性以單下劃線 _ 開頭,表示該屬性僅應(yīng)在類內(nèi)部或其子類中使用。雖然可以從外部訪問,但這通常被視為一種慣例。
私有屬性 (Private)
私有屬性以雙下劃線 __ 開頭,Python 會對這類屬性進(jìn)行名稱改寫(Name Mangling),從而防止從外部直接訪問。
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}" # 測試BankAccount類的功能 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 # 嘗試非法訪問私有屬性 try: print(account.__balance) # 這里會拋出 AttributeError 錯誤 except AttributeError as e: print(e) # 輸出: 'BankAccount' object has no attribute '__balance' # 使用名稱改寫的機(jī)制間接訪問私有屬性 print(account._BankAccount__balance) # 輸出: 80 【不推薦】
單例模式下的封裝應(yīng)用除了基本的數(shù)據(jù)封裝外,在某些場景下可能還需要確保某個類只存在一個實(shí)例。這種需求可以通過重寫 __new__
方法并結(jié)合靜態(tài)變量實(shí)現(xiàn)單例模式。
以下是基于日志管理器的一個簡單示例:
class Logger: _instance = None # 靜態(tài)變量用于存儲唯一實(shí)例 def __new__(cls, *args, **kwargs): if not cls._instance: # 如果尚未創(chuàng)建過實(shí)例,則初始化一個新的實(shí)例 cls._instance = super(Logger, cls).__new__(cls) return cls._instance # 返回已存在的實(shí)例 def log(self, message): print(f"[LOG]: {message}") # 測試Logger類的行為 logger1 = Logger() logger2 = Logger() assert logger1 is logger2 # True,表明兩個引用指向同一個對象 logger1.log("System started.") # 輸出: [LOG]: System started. logger2.log("User logged in.") # 輸出: [LOG]: User logged in.
總結(jié)以上兩段代碼分別演示了常規(guī)封裝技術(shù)和單例設(shè)計模式中的封裝實(shí)踐。前者強(qiáng)調(diào)的是對敏感字段的有效隔離;后者則進(jìn)一步擴(kuò)展到整個類層面,保證資源使用的統(tǒng)一性。
總結(jié)
到此這篇關(guān)于Python中關(guān)鍵字Class的定義和使用方法的文章就介紹到這了,更多相關(guān)Python Class使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python中threading開啟關(guān)閉線程操作
這篇文章主要介紹了python中threading開啟關(guān)閉線程操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05Python設(shè)置Word頁面紙張方向?yàn)闄M向
這篇文章主要為大家詳細(xì)介紹了Python設(shè)置Word頁面紙張方向?yàn)闄M向的相關(guān)知識,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起2024-02-02Python實(shí)現(xiàn)針對json中某個關(guān)鍵字段進(jìn)行排序操作示例
這篇文章主要介紹了Python實(shí)現(xiàn)針對json中某個關(guān)鍵字段進(jìn)行排序操作,涉及Python json數(shù)組排序及l(fā)ambda表達(dá)式相關(guān)操作技巧,需要的朋友可以參考下2018-12-12python tqdm 實(shí)現(xiàn)滾動條不上下滾動代碼(保持一行內(nèi)滾動)
這篇文章主要介紹了python tqdm 實(shí)現(xiàn)滾動條不上下滾動代碼(保持一行內(nèi)滾動),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02使用Python和NLTK進(jìn)行文本預(yù)處理示例詳解
文將介紹如何使用Python編程語言和NLTK(Natural Language Toolkit)庫進(jìn)行文本預(yù)處理,為后續(xù)的文本分析和機(jī)器學(xué)習(xí)任務(wù)做準(zhǔn)備,文中有詳細(xì)的代碼示例供大家參考,需要的朋友可以參考下2024-03-03詳解Python 模擬實(shí)現(xiàn)生產(chǎn)者消費(fèi)者模式的實(shí)例
這篇文章主要介紹了詳解Python 模擬實(shí)現(xiàn)生產(chǎn)者消費(fèi)者模式的實(shí)例的相關(guān)資料,這里使用了線程知識,隊(duì)列知識及循環(huán)的知識,需要的朋友可以參考下2017-08-08