一、面向對象編程
Python中支持面向對象編程,通過使用類和對象的概念可以更好地管理和維護複雜的代碼。在Python中,我們可以通過定義類來創建新的對象。類可以包含屬性和方法,屬性是類的屬性或對象的屬性,方法是類的方法或對象的方法。
1、定義類和對象
定義類時需要使用關鍵字class,後面跟上類名。類名通常採用首字母大寫的命名法。在類中定義方法時,第一個參數必須為self,代表當前對象。定義對象時,需要調用類並將其賦值給變量。
class Dog: def __init__(self, name, age): self.name = name self.age = age def bark(self): print(self.name + "汪汪叫") # 創建對象 my_dog = Dog("旺財", 3) my_dog.bark()
2、繼承和多態
Python支持繼承和多態,通過繼承可以復用已有代碼,通過多態可以增加代碼的靈活性。
# 定義父類 class Animal: def eat(self): print("動物正在吃東西") # 定義子類 class Cat(Animal): def eat(self): print("貓正在吃魚") class Dog(Animal): def eat(self): print("狗正在啃骨頭") # 多態 def feed_animal(animal): animal.eat() cat = Cat() dog = Dog() feed_animal(cat) # 貓正在吃魚 feed_animal(dog) # 狗正在啃骨頭
二、高階函數
Python中函數是一等公民,支持函數作為參數、函數作為返回值、函數內定義函數等高級特性。
1、函數作為參數
在Python中,我們可以將一個函數作為另一個函數的參數,這種函數被稱為高階函數。常見的高階函數有map、filter和reduce。
# map函數:將一個列表中的元素映射成另一個列表 def square(x): return x * x result = map(square, [1, 2, 3, 4, 5]) print(list(result)) # [1, 4, 9, 16, 25] # filter函數:過濾列表中的元素 def is_even(x): return x % 2 == 0 result = filter(is_even, [1, 2, 3, 4, 5]) print(list(result)) # [2, 4] # reduce函數:累積列表中的元素 from functools import reduce def add(x, y): return x + y result = reduce(add, [1, 2, 3, 4, 5]) print(result) # 15
2、函數作為返回值
在Python中,我們可以在一個函數內部定義另一個函數,並將其作為返回值。這種函數被稱為閉包。
def calc_power(n): def inner(x): return x ** n return inner square = calc_power(2) print(square(3)) # 9
三、裝飾器
Python中的裝飾器是一種特殊的函數,用於修改其他函數的行為。常見的裝飾器包括@staticmethod、@classmethod和@property。
1、@staticmethod裝飾器
@staticmethod是一個靜態方法裝飾器,用於定義與類無關的函數。在靜態方法中不需要引用任何類屬性或方法。
class Calculator: @staticmethod def add(x, y): return x + y print(Calculator.add(1, 2)) # 3
2、@classmethod裝飾器
@classmethod是一個類方法裝飾器,用於定義與特定類相關的函數。類方法的第一個參數必須為cls,代表當前類。
class Person: age = 25 @classmethod def getAge(cls): return cls.age print(Person.getAge()) # 25
3、@property裝飾器
@property是一個屬性裝飾器,用於將一個函數轉換為只讀屬性。當訪問該屬性時,會自動調用該函數。
class Person: def __init__(self, age): self._age = age @property def age(self): return self._age p = Person(25) print(p.age) # 25
四、異步編程
Python支持異步編程,通過使用async和await關鍵字可以輕鬆實現異步編程。異步編程可以提高程序的效率和響應速度。
1、異步函數
異步函數使用async關鍵字定義,可以將其看作一個協程(coroutine)。在異步函數中可以使用await關鍵字等待其他協程或異步任務的完成。
import asyncio async def hello(): print("Hello") await asyncio.sleep(1) print("world") await hello() # Hello\n(等待1s)\nworld
2、異步上下文管理器
異步上下文管理器使用async關鍵字定義,通過實現__aenter__和__aexit__方法來支持在異步上下文中使用with語句。
class AsyncFile: def __init__(self, file): self.file = file async def __aenter__(self): self.handle = await asyncio.to_thread(open, self.file, 'r') return self.handle async def __aexit__(self, exc_type, exc, tb): await asyncio.to_thread(self.handle.close) async with AsyncFile('file.txt') as f: print(await asyncio.to_thread(f.read))
以上就是Python基礎3的一些高級特性。通過了解以上內容,我們可以更好地管理和維護代碼,提高程序的效率和可讀性。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/232208.html