1銆侀潰鍚戝璞¤璁″師鍒 ???
1.1 SOLID鍘熷垯绠浠
SOLID鏄潰鍚戝璞¤璁$殑浜斿ぇ鍘熷垯锛岀敱Robert C. Martin鎻愬嚭 锛屾瘡涓瓧姣嶅垎鍒唬琛ㄥ崟涓鑱岃矗鍘熷垯锛圫RP锛夈佸紑鏀惧皝闂師鍒欙紙OCP锛夈侀噷姘忔浛鎹㈠師鍒欙紙LSP锛夈佹帴鍙i殧绂诲師鍒欙紙ISP锛夊拰渚濊禆鍊掔疆鍘熷垯锛圖IP锛夈傞伒寰繖浜涘師鍒欏彲浠ユ瀯寤哄嚭鏇村仴澹佸彲缁存姢鍜屽彲鎵╁睍鐨勮蒋浠剁郴缁熴
1.2 鍗曚竴鑱岃矗鍘熷垯(SRP)
鍗曚竴鑱岃矗鍘熷垯寮鸿皟姣忎釜绫绘垨妯″潡搴旇鍙湁涓涓敼鍙樼殑鍘熷洜銆傝繖鎰忓懗鐫涓涓被鍙礋璐d竴涓姛鑳介鍩 锛屽鏋滈渶瑕佷慨鏀癸紝鍘熷洜搴旇鏄繖涓姛鑳介鍩熺殑鍙樻洿銆備緥濡 锛屼竴涓猆ser绫讳粎璐熻矗鐢ㄦ埛鏁版嵁鐨勫瓨鍌ㄥ拰妫绱紝鑰屼笉娑夊強涓氬姟閫昏緫銆
class User:
def __init__(self, id, name):
self.id = id
self.name = name
def get_user_info(self):
return {"id": self.id, "name": self.name}
1.3 寮鏀惧皝闂師鍒(OCP)
寮鏀惧皝闂師鍒欐彁鍊¤蒋浠跺疄浣擄紙绫汇佹ā鍧椼佸嚱鏁扮瓑锛夊簲璇ュ鎵╁睍寮鏀 锛屽淇敼灏侀棴銆傚嵆鍦ㄤ笉淇敼鍘熸湁浠g爜鐨勫熀纭涓婏紝閫氳繃娣诲姞鏂扮殑浠g爜鏉ュ寮哄姛鑳姐傝繖閫氬父閫氳繃缁ф壙鍜屾帴鍙e疄鐜般
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
# 鏂板鍦嗗舰鏃犻渶淇敼Rectangle
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * (self.radius ** 2)
1.4 閲屾皬鏇挎崲鍘熷垯(LSP)
閲屾皬鏇挎崲鍘熷垯鎸囧嚭锛屽湪杞欢涓 锛屽瓙绫诲瀷蹇呴』鑳藉鏇挎崲鎺夊畠浠殑鐖剁被鍨嬶紝鑰屼笉浼氬奖鍝嶇▼搴忕殑姝g‘鎬с傛崲鍙ヨ瘽璇 锛屼娇鐢ㄧ埗绫荤殑鍦版柟锛岄兘鑳介忔槑鍦颁娇鐢ㄥ叾瀛愮被鐨勫璞★紝涓嶄細寮曞彂寮傚父鎴栭敊璇涓恒
class Bird:
def fly(self):
print("Flying...")
class Pigeon(Bird):
def fly(self):
super().fly() # 缁ф壙骞跺彲鑳藉寮哄姛鑳
bird = Bird()
pigeon = Pigeon()
bird.fly() # 杈撳嚭: Flying...
pigeon.fly() # 杈撳嚭: Flying...
1.5 鎺ュ彛闅旂鍘熷垯(ISP)
鎺ュ彛闅旂鍘熷垯寤鸿瀹㈡埛绔笉搴斾緷璧栧畠涓嶉渶瑕佺殑鎺ュ彛銆傛帴鍙e簲璇ュ敖鍙兘缁嗗寲 锛屼互淇濊瘉瀹㈡埛绔粎渚濊禆浜庡畠瀹為檯浣跨敤鐨勫姛鑳姐傝繖鍙互閫氳繃瀹氫箟澶氫釜涓撻棬鐨勬帴鍙h屼笉鏄竴涓簽澶ц噧鑲跨殑鎺ュ彛鏉ュ疄鐜般
from typing import Protocol
class Drawable(Protocol):
def draw(self):
...
class Printable(Protocol):
def print_details(self):
...
class Shape(Drawable, Printable):
def draw(self):
print("Drawing the shape...")
def print_details(self):
print("Printing shape details...")
1.6 渚濊禆鍊掔疆鍘熷垯(DIP)
渚濊禆鍊掔疆鍘熷垯鍊″楂樺眰妯″潡涓嶅簲渚濊禆浜庝綆灞傛ā鍧楋紝浜岃呴兘搴旇渚濊禆浜庢娊璞°傛娊璞′笉搴旇渚濊禆浜庡叿浣撳疄鐜帮紝鍏蜂綋瀹炵幇搴旇渚濊禆浜庢娊璞°傝繖閫氬父閫氳繃渚濊禆娉ㄥ叆绛夋柟寮忓疄鐜般
from abc import ABC, abstractmethod
class Notification(ABC):
@abstractmethod
def send(self, message: str):
pass
class EmailNotification(Notification):
def send(self, message: str):
print(f"Sending email: {message}")
class SMSNotification(Notification):
def send(self, message: str):
print(f"Sending SMS: {message}")
class NotificationService:
def __init__(self, notification: Notification):
self.notification = notification
def notify_user(self, user_id: int, message: str):
self.notification.send(message)
# 浣跨敤鏃 锛岄夋嫨鍏蜂綋鐨勯氱煡鏂瑰紡
service = NotificationService(EmailNotification())
service.notify_user(1, "Hello, this is an email notification.")
閬靛惊杩欎簺鍘熷垯锛屼綘鐨凱ython浠g爜灏嗘洿鍔犲仴澹佺伒娲伙紝涓旀槗浜庣淮鎶ゃ
2銆佷娇鐢ˊclassmethod涓嶡staticmethod ???
2.1 绫绘柟娉曚紭鍖栦唬鐮佺粨鏋
绫绘柟娉曢氳繃@classmethod瑁呴グ鍣ㄥ畾涔夛紝瀹冩帴鏀朵竴涓殣鍚殑鍙傛暟cls 锛屼唬琛ㄧ被鏈韩鑰屼笉鏄被鐨勫疄渚嬨傝繖绉嶆柟娉曢傜敤浜庨偅浜涙搷浣滃睘浜庣被绾у埆鑰岄潪鐗瑰畾瀹炰緥鐨勫姛鑳斤紝姣斿宸ュ巶鏂规硶鎴栬呭鐞嗙被鍙橀噺銆傚畠鏈夊姪浜庡噺灏戜唬鐮佸啑浣欙紝鎻愰珮浠g爜鐨勭粍缁囨у拰鍙鎬с
class Pizza:
toppings = ["cheese", "tomato"]
@classmethod
def add_default_topping(cls, topping):
cls.toppings.append(topping)
@classmethod
def get_available_toppings(cls):
return cls.toppings
Pizza.add_default_topping("mushroom")
print(Pizza.get_available_toppings()) # 杈撳嚭: ['cheese', 'tomato', 'mushroom']
2.2 闈欐佹柟娉曟彁鍗囨ā鍧楁
闈欐佹柟娉曢氳繃@staticmethod瑁呴グ鍣ㄥ畾涔夛紝瀹冧笉鎺ユ敹闅愬惈鐨剆elf鎴朿ls鍙傛暟銆傝繖绫绘柟娉曢氬父涓庣被鐨勫疄渚嬫棤鍏筹紝鍙互瑙嗕负涓庣被鍏宠仈鐨勫嚱鏁帮紝鐢ㄤ簬缁勭粐閫昏緫鎴栨彁渚涘伐鍏峰嚱鏁 锛屾彁鍗囦唬鐮佹ā鍧楀寲銆
class MathUtils:
@staticmethod
def add(a, b):
return a + b
result = MathUtils.add(5, 3)
print(result) # 杈撳嚭: 8
2.3 瀹炰緥鏂规硶涓庣被鏂规硶瀵规瘮搴旂敤
瀹炰緥鏂规硶鐩存帴鎿嶄綔瀹炰緥鍙橀噺锛岄氳繃self寮曠敤瀹炰緥鏈韩銆傜被鏂规硶鍒欐搷浣滅被鍙橀噺锛岄氳繃cls寮曠敤绫汇傞夋嫨鍝鏂规硶鍙栧喅浜庢搷浣滅殑鏁版嵁鑼冨洿鍜岀洰鐨勩傞潤鎬佹柟娉曞垯鐙珛浜庣被瀹炰緥鍜岀被鍙橀噺锛岄傜敤浜庨氱敤鍑芥暟銆
? 瀹炰緥鏂规硶绀轰緥:
class BankAccount:
def __init__(self, balance=0):
self.balance = balance
def deposit(self, amount):
self.balance += amount
return self.balance
account = BankAccount()
print(account.deposit(100)) # 杈撳嚭: 100
? 绫绘柟娉曚笌瀹炰緥鏂规硶瀵规瘮:
class Counter:
count = 0
def __init__(self):
Counter.increment_count()
@classmethod
def increment_count(cls):
cls.count += 1
def show_count(self):
print(f"Instance Count: {self.count}")
counter1 = Counter()
counter2 = Counter()
counter1.show_count() # 杈撳嚭: Instance Count: 2
鍦ㄨ繖涓緥瀛愪腑锛宨ncrement_count浣滀负绫绘柟娉曪紝姣忔鍒涘缓Counter瀹炰緥鏃堕兘浼氬鍔犵被鍙橀噺count鐨勫 锛屼綋鐜颁簡绫绘柟娉曞湪绠$悊绫荤姸鎬佷笂鐨勪綔鐢 锛岃宻how_count浣滀负瀹炰緥鏂规硶锛屽睍绀轰簡褰撳墠瀹炰緥瀵瑰簲鐨勭被鍙橀噺鍊硷紝浣嗕笉浼氱洿鎺ヤ慨鏀圭被鍙橀噺銆
3銆佽楗板櫒娣卞叆杩愮敤 ??
3.1 绠鍖栨棩蹇楄褰
瑁呴グ鍣ㄥ彲浠ョ畝鍖栦唬鐮佷腑鐨勬棩蹇楄褰曡繃绋嬶紝鏃犻渶鍦ㄦ瘡涓嚱鏁板紑濮嬪拰缁撴潫澶勬墜鍔ㄦ坊鍔犳棩蹇椾唬鐮併傞氳繃瀹氫箟涓涓棩蹇楄楗板櫒 锛屽彲浠ヨ嚜鍔ㄦ崟鑾峰嚱鏁扮殑鎵ц鏃堕棿銆佽緭鍏ュ弬鏁板強杩斿洖鍊硷紝浠庤屾彁楂樹唬鐮佺殑鍙淮鎶ゆу拰鍙鎬с
import time
import functools
def log_decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"{func.__name__} ran in: {end_time - start_time}s")
return result
return wrapper
@log_decorator
def example_function(x, y):
time.sleep(1) # 妯℃嫙鑰楁椂鎿嶄綔
return x + y
print(example_function(3, 4))
3.2 鎬ц兘鐩戞帶涓庡害閲
鎬ц兘鐩戞帶瑁呴グ鍣ㄥ彲浠ュ府鍔╁紑鍙戣呭揩閫熻瘑鍒唬鐮佷腑鐨勭摱棰堛傞氳繃鍦ㄥ叧閿嚱鏁颁笂搴旂敤姝ょ被瑁呴グ鍣 锛屽彲浠ユ敹闆嗘墽琛屾椂闂淬佽祫婧愪娇鐢ㄦ儏鍐电瓑鏁版嵁锛岃繘鑰屼紭鍖栨ц兘銆
def performance_monitor(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"{func.__name__}: Execution Time: {end_time - start_time} seconds")
return result
return wrapper
@performance_monitor
def heavy_computation(n):
sum = 0
for i in range(n):
sum += i
return sum
heavy_computation(1000000)
3.3 鍔ㄦ佷慨鏀圭被琛屼负
瑁呴グ鍣ㄥ悓鏍疯兘鐢ㄤ簬鍔ㄦ佷慨鏀圭被鐨勮涓猴紝濡傚湪绫绘柟娉曚笂娣诲姞鏉冮檺妫鏌ャ佷簨鍔$鐞嗙瓑銆傞氳繃鍏冪被鍜岃楗板櫒鐨勭粍鍚堬紝鍙互鍦ㄧ被瀹氫箟闃舵灏变粙鍏ワ紝涓虹被鏂规硶娣诲姞棰濆鐨勫姛鑳斤紝鑰屾棤闇淇敼鍘熸湁鏂规硶鐨勪唬鐮併
class AccessControlMeta(type):
def __new__(cls, name, bases, dct):
for attr_name, attr_value in dct.items():
if callable(attr_value):
dct[attr_name] = check_permissions(attr_value)
return super().__new__(cls, name, bases, dct)
def check_permissions(func):
def wrapper(self, *args, **kwargs):
if not self.user.has_permission('read'):
raise PermissionError("Access denied.")
return func(self, *args, **kwargs)
return wrapper
class SecureDocument(metaclass=AccessControlMeta):
def __init__(self, user):
self.user = user
def read_content(self):
return "Confidential Document Content"
document = SecureDocument(User('Alice'))
try:
print(document.read_content())
except PermissionError as e:
print(e)
閫氳繃涓婅堪绀轰緥 锛屽彲浠ョ湅鍒拌楗板櫒鍦ㄧ畝鍖栨棩蹇楄褰曘佹ц兘鐩戞帶涓庡害閲 锛屼互鍙婂姩鎬佷慨鏀圭被琛屼负鏂归潰鐨勫己澶у姛鑳斤紝鏈夋晥鎻愬崌浜嗕唬鐮佺殑鐏垫椿鎬у拰鍙淮鎶ゆс
4銆佺户鎵夸笌澶氭佷紭鍖栦唬鐮佸鐢 ??
4.1 璁捐鐏垫椿鐨勭户鎵跨粨鏋
缁ф壙鍏佽鎴戜滑瀹氫箟涓涓被锛堝瓙绫伙級缁ф壙鍙︿竴涓被锛堢埗绫伙級鐨勫睘鎬у拰鏂规硶锛屼粠鑰屽疄鐜颁唬鐮佸鐢ㄥ拰妯″潡鍖栬璁°備竴涓壇濂界殑缁ф壙缁撴瀯搴旇娓呮櫚鍦拌〃杈剧被涔嬮棿鐨勨渋s-a鈥濆叧绯 锛屼娇寰楀瓙绫昏嚜鐒舵墿灞曠埗绫荤殑鍔熻兘锛屽悓鏃朵繚鎸佹帴鍙g殑涓鑷存с
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclass must implement abstract method")
class Dog(Animal):
def speak(self):
return f'{self.name} says Woof!'
class Cat(Animal):
def speak(self):
return f'{self.name} says Meow!'
fido = Dog('Fido')
garfield = Cat('Garfield')
print(fido.speak()) # 杈撳嚭: Fido says Woof!
print(garfield.speak()) # 杈撳嚭: Garfield says Meow!
4.2 澶氭佸噺灏戞潯浠跺垽鏂
澶氭佹剰鍛崇潃涓涓帴鍙e彲浠ユ湁澶氱瀹炵幇鏂瑰紡 锛屽畠閫氳繃鎶借薄鍩虹被鎴栨帴鍙e畾涔夌粺涓鐨勮涓猴紝璁╀笉鍚岀被鍨嬬殑瀵硅薄鑳藉鍝嶅簲鐩稿悓鐨勬秷鎭紝浠庤屽噺灏戠▼搴忎腑鐨勬潯浠跺垎鏀垽鏂紝浣夸唬鐮佹洿鍔犵畝娲併佹槗浜庢墿灞曘
def animal_sound(animal):
print(animal.speak())
animal_sound(fido) # 杈撳嚭: Fido says Woof!
animal_sound(garfield) # 杈撳嚭: Garfield says Meow!
鍦ㄨ繖涓緥瀛愪腑锛宎nimal_sound鍑芥暟骞朵笉鍏冲績浼犲叆鐨勫叿浣撳璞$被鍨 锛屽彧瑕佽瀵硅薄瀹炵幇浜唖peak鏂规硶 锛屽嵆鍙纭墽琛 锛岃繖灏辨槸澶氭佹х殑浣撶幇銆
4.3 鎶借薄鍩虹被寮哄寲鎺ュ彛涓鑷存
鎶借薄鍩虹被锛圓BC锛夐氳繃瀹氫箟涓缁勬娊璞℃柟娉曟潵寮哄埗瀛愮被閬靛惊鏌愮瑙勮寖锛岀‘淇濇墍鏈夊瓙绫诲叿鏈夌浉鍚岀殑鎺ュ彛锛屽嵆浣垮畠浠殑瀹炵幇缁嗚妭涓嶅悓銆傝繖鏈夊姪浜庣淮鎸佸ぇ鍨嬮」鐩腑浠g爜鐨勪竴鑷存у拰鍙淮鎶ゆс
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * (self.radius ** 2)
def perimeter(self):
return 2 * 3.14 * self.radius
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
def perimeter(self):
return 4 * self.side
shapes = [Circle(5), Square(10)]
for shape in shapes:
print(f"Area: {shape.area()}, Perimeter: {shape.perimeter()}")
閫氳繃瀹氫箟Shape鎶借薄鍩虹被骞跺0鏄巃rea鍜宲erimeter涓烘娊璞℃柟娉曪紝纭繚浜嗕换浣曠户鎵胯嚜Shape鐨勭被閮藉繀椤诲疄鐜拌繖涓や釜鏂规硶锛屼粠鑰屽湪涓嶅悓鐨勫舰鐘朵箣闂翠繚鎸佷簡涓鑷寸殑鎺ュ彛銆
5銆佹彃浠跺寲璁捐妯″紡 ??
5.1 鎻掍欢鏋舵瀯鍩虹
鎻掍欢鏋舵瀯鏄竴绉嶈璁℃ā寮忥紝瀹冨厑璁哥▼搴忓湪杩愯鏃跺姩鎬佸姞杞藉拰浣跨敤澶栭儴缁勪欢锛堟彃浠讹級 锛屼互姝ゆ潵鎵╁睍鍔熻兘鎴栧畾鍒惰涓恒傛牳蹇冩濇兂鏄垎绂诲叧娉ㄧ偣锛屼娇涓诲簲鐢ㄤ繚鎸佽交閲忓寲 锛屽悓鏃舵敮鎸佺伒娲荤殑鎵╁睍銆傚疄鐜拌繖涓妯″紡鐨勫叧閿湪浜庡畾涔夋竻鏅扮殑鎺ュ彛鍜屽彂鐜般佸姞杞芥彃浠剁殑鏈哄埗銆
5.2 瀹炵幇鐑彃鎷斿姛鑳
鐑彃鎷旀剰鎸囧湪绯荤粺杩愯鏃舵坊鍔犮佺Щ闄ゆ垨鏇挎崲缁勪欢鑰屾棤闇閲嶅惎绯荤粺銆傚湪Python涓紝鍙互鍒╃敤鍙嶅皠鍜屽姩鎬佸鍏ユā鍧楁潵瀹炵幇杩欎竴鐗规с
import importlib
import os
class PluginManager:
def __init__(self, plugin_folder='plugins'):
self.plugins = []
self.plugin_folder = plugin_folder
self.discover_plugins()
def discover_plugins(self):
for filename in os.listdir(self.plugin_folder):
if filename.endswith('.py') and filename != '__init__.py':
module_name = filename[:-3]
module = importlib.import_module(f"{self.plugin_folder}.{module_name}")
self.load_plugin(module)
def load_plugin(self, module):
if hasattr(module, 'execute'):
self.plugins.append(module)
print(f"Loaded plugin: {module.__name__}")
def run_plugins(self):
for plugin in self.plugins:
plugin.execute()
# 鍋囪鏈変竴涓彃浠剁洰褰曠粨鏋勫涓嬶細
# plugins/
# 鈹溾攢鈹 plugin_a.py
# 鈹斺攢鈹 plugin_b.py
manager = PluginManager()
manager.run_plugins()
鍦ㄨ繖涓緥瀛愪腑 锛孭luginManager绫讳細鑷姩鍙戠幇骞跺姞杞芥寚瀹氱洰褰曚笅鐨勬彃浠舵枃浠讹紙鎺掗櫎__init__.py锛夛紝鍙杩欎簺鎻掍欢鏂囦欢瀹氫箟浜嗕竴涓悕涓篹xecute鐨勬柟娉曘
5.3 鎵╁睍鎬т笌缁存姢鎬ф彁鍗
閲囩敤鎻掍欢鍖栬璁℃樉钁楀寮轰簡杞欢鐨勬墿灞曟у拰缁存姢鎬с傛柊鍔熻兘鍙互閫氳繃缂栧啓鏂扮殑鎻掍欢鏉ユ坊鍔狅紝鑰屾棤闇淇敼鏍稿績浠g爜锛岃繖闄嶄綆浜嗚﹀悎搴︼紝渚夸簬鐙珛寮鍙戝拰娴嬭瘯鎻掍欢銆傚悓鏃 锛屽浜庣淮鎶ゆ潵璇达紝姣忎釜鎻掍欢閮芥槸涓涓浉瀵圭嫭绔嬬殑鍗曞厓锛屾洿鏂版垨淇鏌愪釜鍔熻兘鏃跺彧闇鍏虫敞鐩稿叧鐨勬彃浠跺嵆鍙紝鎻愰珮浜嗛棶棰樺畾浣嶅拰瑙e喅鐨勬晥鐜囥
姝ゅ 锛岃壇濂界殑鎻掍欢绠$悊杩樺寘鎷増鏈帶鍒躲佸畨鍏ㄦф鏌ュ拰鎻掍欢闂寸殑渚濊禆绠$悊锛岃繖浜涢兘鏄繚闅滄彃浠剁郴缁熼暱鏈熺ǔ瀹氳繍琛岀殑鍏抽敭鍥犵礌銆傞氳繃瀹氫箟娓呮櫚鐨勬彃浠舵帴鍙h鑼冨拰鎻愪緵瀹屽杽鐨勬枃妗f敮鎸侊紝寮鍙戣呯ぞ鍖哄彲浠ユ洿瀹规槗鍦拌础鐚拰鍏变韩鎻掍欢锛岃繘涓姝ユ帹鍔ㄨ蒋浠剁敓鎬佺殑绻佽崳銆
6銆佸厓绫讳笌鑷畾涔夌被鍒涘缓 ??
6.1 鍏冪被鍩虹涓庡簲鐢ㄥ満鏅
鍏冪被锛圡etaclass锛夋槸Python涓殑涓绉嶉珮绾х壒鎬э紝瀹冩帶鍒剁潃绫荤殑鍒涘缓杩囩▼銆傜畝鍗曟潵璇达紝鍏冪被灏辨槸鈥滅被鐨勭被鈥 锛屽綋浣犲畾涔変竴涓被鏃讹紝Python瀹為檯涓婇氳繃鍏冪被鏉ュ垱寤鸿繖涓被銆傞粯璁ゆ儏鍐典笅 锛屾墍鏈夌被閮戒娇鐢╰ype浣滀负鍏冪被锛屼絾浣犲彲浠ヨ嚜瀹氫箟鍏冪被鏉ユ敼鍙樼被鐨勭敓鎴愭柟寮忔垨璧嬩簣绫荤壒娈婅涓恒
搴旂敤鍦烘櫙鍖呮嫭浣嗕笉闄愪簬锛
? 鍔ㄦ佷慨鏀规垨澧炲姞绫诲睘鎬у拰鏂规硶銆
? 瀹炵幇绫荤殑娉ㄥ唽鏈哄埗 锛岃嚜鍔ㄨ拷韪垨绠$悊绫汇
? 瀹炵幇鍗曚緥妯″紡鎴栧伐鍘傛ā寮忋
? 鑷姩娣诲姞绫诲瀷妫鏌ユ垨鍏朵粬褰㈠紡鐨勯獙璇併
6.2 鍔ㄦ佺敓鎴愮被
鍏冪被鍏佽鍦ㄨ繍琛屾椂鍔ㄦ佺敓鎴愮被锛岃繖瀵逛簬妗嗘灦鎴栧簱鐨勫紑鍙戣呯壒鍒湁鐢紝浠栦滑鍙互鍩轰簬閰嶇疆鎴栫敤鎴疯緭鍏ュ垱寤虹被銆
class Meta(type):
def __new__(cls, name, bases, dct):
# 鍔ㄦ佹坊鍔犲睘鎬
dct['additional_attribute'] = 'Dynamic Addition'
return super().__new__(cls, name, bases, dct)
class MyClass(metaclass=Meta):
pass
print(MyClass.additional_attribute) # 杈撳嚭: Dynamic Addition
6.3 绫诲睘鎬т笌瀹炰緥灞炴х鐞
鍏冪被杩樺彲浠ョ敤鏉ョ鐞嗙被灞炴у拰瀹炰緥灞炴 锛屾瘮濡傝嚜鍔ㄤ负姣忎釜绫诲睘鎬ф坊鍔犻獙璇侀昏緫 锛屾垨鍦ㄥ疄渚嬪寲鏃跺姩鎬佽缃粯璁ゅ笺
class ValidatingMeta(type):
def __new__(cls, name, bases, dct):
# 閬嶅巻骞堕獙璇佺被灞炴
for attr_name, attr_value in dct.items():
if not callable(attr_value) and not attr_name.startswith("__"):
if not isinstance(attr_value, int):
raise TypeError(f"{attr_name} must be an integer")
return super().__new__(cls, name, bases, dct)
class ValidateClass(metaclass=ValidatingMeta):
static_int = 10
invalid_attribute = "Should error out"
try:
class MyClass(ValidateClass):
pass
except TypeError as e:
print(e) # 搴旇緭鍑洪敊璇俊鎭紝鍥犱负"invalid_attribute"涓嶆槸鏁存暟
鍦ㄤ笂闈㈢殑渚嬪瓙涓 锛孷alidatingMeta鍏冪被鍦ㄥ垱寤虹被鏃舵鏌ユ墍鏈夐潪鏂规硶銆侀潪绉佹湁鐨勭被灞炴ф槸鍚︿负鏁存暟 锛岃嫢涓嶆槸锛屽垯鎶涘嚭TypeError寮傚父銆傝繖灞曠ず浜嗗厓绫诲湪纭繚浠g爜璐ㄩ噺鍜屼竴鑷存х殑寮哄ぇ鑳藉姏銆
7銆佷娇鐢 descriptors 绮剧粏鍖栧睘鎬ф帶鍒 ??
7.1 浠涔堟槸descriptors
鎻忚堪绗︼紙Descriptors锛夋槸Python涓竴绉嶅己澶х殑鏈哄埗锛岀敤浜庡疄鐜板睘鎬х殑鑷畾涔夎闂帶鍒躲傛弿杩扮瀹炶川涓婃槸涓涓疄鐜颁簡鐗瑰畾鍗忚鐨勭被锛岃繖涓崗璁寘鎷琠_get__()銆乢_set__()鍜宊_delete__()鏂规硶涓殑涓涓垨澶氫釜銆傚綋鎻忚堪绗︾被鐨勫疄渚嬭鐢ㄤ綔鍙︿竴涓被鐨勬垚鍛樻椂锛屾弿杩扮鍗忚灏嗚鐩栭粯璁ょ殑灞炴ц闂涓猴紝鍏佽瀵瑰睘鎬х殑鑾峰彇銆佽缃拰鍒犻櫎杩涜瀹氬埗鍖栫鐞嗐
7.2 灞炴ч獙璇佷笌杞崲
鎻忚堪绗﹀彲浠ョ敤鏉ュ湪璁剧疆灞炴у煎墠杩涜楠岃瘉锛岀‘淇濇暟鎹殑涓鑷存у拰鍚堟硶鎬э紝涔熷彲浠ュ湪鑾峰彇灞炴у兼椂杩涜绫诲瀷杞崲鎴栧鐞嗐
class PositiveInt:
def __set_name__(self, owner, name):
self.name = name
def __get__(self, instance, owner):
return getattr(instance, self.name, 0)
def __set__(self, instance, value):
if not isinstance(value, int) or value < 0:
raise ValueError(f"{self.name} must be a positive integer")
setattr(instance, self.name, value)
class MyClass:
age = PositiveInt()
person = MyClass()
person.age = 25 # 姝g‘璁剧疆
print(person.age) # 杈撳嚭: 25
try:
person.age = -1 # 灏濊瘯璁剧疆璐熷硷紝灏嗘姏鍑哄紓甯
except ValueError as e:
print(e) # 杈撳嚭: age must be a positive integer
7.3 鑷姩鍖栧睘鎬х鐞
鎻忚堪绗﹁繕鑳藉府鍔╄嚜鍔ㄥ寲澶嶆潅鐨勫睘鎬х鐞嗭紝姣斿缂撳瓨璁$畻灞炴х殑缁撴灉銆佹棩蹇楄褰曘佹潈闄愭帶鍒剁瓑銆
class CachedProperty:
def __init__(self, func):
self.func = func
def __get__(self, instance, owner):
if instance is None:
return self
value = self.func(instance)
setattr(instance, self.func.__name__, value)
return value
class Circle:
def __init__(self, radius):
self.radius = radius
@CachedProperty
def area(self):
print("Calculating area...")
return 3.14 * (self.radius ** 2)
circle = Circle(5)
print(circle.area) # 杈撳嚭: Calculating area... \n 78.5
print(circle.area) # 杈撳嚭: 78.5锛屼笉鍐嶉噸鏂拌绠
鍦ㄨ繖涓緥瀛愪腑锛孋achedProperty鎻忚堪绗︾敤浜庣紦瀛榓rea灞炴х殑璁$畻缁撴灉 锛岄伩鍏嶉噸澶嶈绠楋紝鎻愰珮浜嗘晥鐜囥傛弿杩扮鐨勫己澶т箣澶勫湪浜庡畠浠兘澶熸彁渚涚粏绮掑害鐨勬帶鍒讹紝璁╁睘鎬ц闂彉寰楁棦鐏垫椿鍙堝己澶с
8銆丳ython鏁版嵁绫荤殑楂樻晥鍒╃敤 ??
8.1 鏁版嵁绫昏嚜鍔ㄥ疄鐜伴瓟娉曟柟娉
Python鐨勬暟鎹被锛坉ataclasses妯″潡锛夋彁渚涗簡涓绉嶇畝娲佺殑鏂瑰紡鏉ュ畾涔夌被锛岃嚜鍔ㄤ负绫绘坊鍔燺_init__銆乢_repr__銆乢_eq__绛夐瓟娉曟柟娉 锛屾瀬澶у湴绠鍖栦簡鍒涘缓绠鍗曟暟鎹鍣ㄧ殑杩囩▼銆
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
p1 = Point(3.0, 4.0)
p2 = Point(3.0, 4.0)
print(p1) # 杈撳嚭: Point(x=3.0, y=4.0)
print(p1 == p2) # 杈撳嚭: True
杩欐浠g爜涓 锛孈dataclass瑁呴グ鍣ㄨ嚜鍔ㄤ负Point绫荤敓鎴愪簡鍒濆鍖栨柟娉曘佸瓧绗︿覆琛ㄧず鏂规硶浠ュ強鐩哥瓑鎬ф瘮杈冩柟娉曪紝鏃犻渶鎵嬪姩瀹炵幇銆
8.2 鏁版嵁绫讳笌鍛藉悕鍏冪粍姣旇緝
鍛藉悕鍏冪粍锛坱yping.NamedTuple锛変篃鏄竴绉嶈〃绀轰笉鍙彉鏁版嵁缁撴瀯鐨勬柟寮忥紝浣嗗畠鍩轰簬鍏冪粍涓斿睘鎬т笉鍙慨鏀广傛暟鎹被鍒欐彁渚涗簡鏇村鐨勭伒娲绘э紝鏀寔瀛楁榛樿鍊笺佺被鍨嬫敞瑙e拰鍙夌殑鍙彉鎬с
from typing import NamedTuple
class NamedPoint(NamedTuple):
x: float
y: float = 0.0 # 榛樿鍊煎湪鍛藉悕鍏冪粍涓笉鍙敤
np = NamedPoint(3.0)
# 鏁版嵁绫绘敮鎸侀粯璁ゅ
@dataclass
class DefaultPoint:
x: float
y: float = 0.0
dp = DefaultPoint(3.0)
8.3 鏁版嵁绫荤殑缁ф壙涓庢墿灞
鏁版嵁绫绘敮鎸佺户鎵匡紝骞朵笖鍙互鍦ㄥ瓙绫讳腑缁х画浣跨敤dataclass瑁呴グ鍣ㄦ潵鎵╁睍鎴栬鐩栫埗绫荤殑瀛楁銆
@dataclass
class BasePoint:
x: float
y: float
@dataclass
class ColorPoint(BasePoint):
color: str = "red"
cp = ColorPoint(1.0, 2.0)
print(cp) # 杈撳嚭: ColorPoint(x=1.0, y=2.0, color='red')
鍦ㄨ繖涓緥瀛愪腑锛孋olorPoint缁ф壙浜咮asePoint 锛屽苟鏂板浜嗕竴涓猚olor瀛楁锛屽睍绀轰簡鏁版嵁绫诲湪绫荤粨鏋勬墿灞曚笂鐨勪究鍒╂с傞氳繃杩欑鏂瑰紡锛屾暟鎹被鑳藉閫傚簲鏇村鏉傜殑鏁版嵁妯″瀷闇姹傦紝鍚屾椂淇濇寔浠g爜鐨勭畝娲佸拰鏄撹鎬с
9銆佸苟鍙戠紪绋嬩紭鍖栨ц兘 ??
9.1 澶氱嚎绋嬩笌绾跨▼姹
澶氱嚎绋嬪厑璁哥▼搴忓悓鏃舵墽琛屽涓换鍔★紝姣忎釜浠诲姟鍦ㄤ竴涓崟鐙殑绾跨▼涓繍琛屻侾ython鏍囧噯搴撲腑鐨則hreading妯″潡鎻愪緵浜嗗绾跨▼鏀寔銆傜嚎绋嬫睜鏄竴绉嶉鍏堝垱寤轰竴缁勭嚎绋嬬殑鎶鏈紝浠诲姟鍒版潵鏃剁洿鎺ュ垎閰嶇粰绾跨▼鎵ц 锛岄伩鍏嶉绻佸垱寤洪攢姣佺嚎绋嬬殑寮閿銆
import threading
from concurrent.futures import ThreadPoolExecutor
def task(identifier):
print(f"Task {identifier} running in {threading.current_thread().name}")
with ThreadPoolExecutor(max_workers=4) as executor:
for i in range(10):
executor.submit(task, i)
9.2 寮傛IO涓巃sync/await
寮傛IO锛堥潪闃诲IO锛夊厑璁哥▼搴忓湪绛夊緟IO鎿嶄綔瀹屾垚鐨勫悓鏃舵墽琛屽叾浠栦换鍔★紝鎻愰珮鏁堢巼銆侾ython 3.5寮曞叆浜哸syncio搴撳拰async/await璇硶锛岀畝鍖栦簡寮傛缂栫▼銆
import asyncio
async def async_task(identifier):
print(f"Async Task {identifier} starting in {asyncio.current_task().get_name()}")
await asyncio.sleep(1) # 妯℃嫙IO鎿嶄綔
print(f"Async Task {identifier} finished")
async def main():
tasks = [asyncio.create_task(async_task(i)) for i in range(3)]
await asyncio.gather(*tasks)
asyncio.run(main())
9.3 骞跺彂瀹夊叏涓庨攣鏈哄埗
骞跺彂鐜涓嬶紝澶氫釜绾跨▼鎴栦换鍔″彲鑳藉悓鏃惰闂叡浜祫婧愶紝瀵艰嚧鏁版嵁涓嶄竴鑷淬備负淇濊瘉骞跺彂瀹夊叏锛岄渶瑕佷娇鐢ㄥ悓姝ュ師璇 锛屽閿侊紙Lock锛夈
import threading
class Counter:
def __init__(self):
self.count = 0
self.lock = threading.Lock()
def increment(self):
with self.lock:
self.count += 1
def worker(counter):
for _ in range(100000):
counter.increment()
counter = Counter()
threads = [threading.Thread(target=worker, args=(counter,)) for _ in range(10)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
print(f"Final count: {counter.count}") # 搴旇緭鍑1000000
鍦ㄤ笂杩扮ず渚嬩腑 锛寃ith self.lock: 浣跨敤浜嗕笂涓嬫枃绠$悊鍣ㄦ潵鑷姩鑾峰彇鍜岄噴鏀鹃攣锛岀‘淇濅簡increment鏂规硶鐨勫師瀛愭э紝闃叉浜嗗苟鍙戝啿绐併傛纭娇鐢ㄩ攣鍜屽叾浠栧悓姝ユ満鍒舵槸骞跺彂缂栫▼涓繚璇佹暟鎹竴鑷存х殑鍏抽敭銆
10銆佷娇鐢╬roperty浼橀泤绠$悊灞炴 ??
10.1 property瑁呴グ鍣ㄥ熀纭
property瑁呴グ鍣ㄥ厑璁稿皢鏂规硶杞彉涓哄睘鎬ц闂殑褰㈠紡锛屼粠鑰屾彁渚涙洿绠娲併佹洿绗﹀悎闈㈠悜瀵硅薄鍘熷垯鐨勬帴鍙c傚畠鏀寔瀹氫箟getter銆乻etter鍜宒eleter鏂规硶锛岃屽閮ㄨ皟鐢ㄦ椂灏卞儚鐩存帴鎿嶄綔灞炴т竴鏍枫
class Celsius:
def __init__(self, temperature=0):
self._temperature = temperature
@property
def temperature(self):
return self._temperature
@temperature.setter
def temperature(self, value):
if value < -273.15:
raise ValueError("Temperature below -273.15 is not possible")
self._temperature = value
c = Celsius()
c.temperature = 37 # 浣跨敤setter璁剧疆娓╁害
print(c.temperature) # 浣跨敤getter鑾峰彇娓╁害 锛岃緭鍑: 37
10.2 灞炴ц闂帶鍒
閫氳繃property 锛屾垜浠彲浠ヨ交鏉惧疄鐜板睘鎬ц闂帶鍒 锛屾瘮濡傛鏌ユ暟鎹殑鏈夋晥鎬с佹墽琛岄澶栭昏緫绛夛紝鑰屾棤闇鏆撮湶鍐呴儴瀹炵幇缁嗚妭銆
class Account:
def __init__(self, balance=0):
self._balance = balance
@property
def balance(self):
"""杩斿洖璐︽埛浣欓"""
return self._balance
@balance.setter
def balance(self, amount):
"""璁剧疆璐︽埛浣欓锛屼笉鍏佽璐熸暟瀛樻"""
if amount < 0:
raise ValueError("Balance cannot be negative")
self._balance = amount
account = Account()
account.balance = 100 # 姝e父璁剧疆
print(account.balance) # 杈撳嚭: 100
try:
account.balance = -50 # 灏濊瘯璁剧疆璐熸暟 锛屽皢鎶涘嚭寮傚父
except ValueError as e:
print(e) # 杈撳嚭: Balance cannot be negative
10.3 鑷畾涔塻etter涓巊etter
property杩樺厑璁告垜浠畾涔夎嚜瀹氫箟鐨刧etter鍜宻etter閫昏緫锛岃繖鏍峰彲浠ュ湪鑾峰彇鎴栬缃睘鎬у兼椂鎵ц棰濆鐨勬搷浣 锛屽鏃ュ織璁板綍銆佸崟浣嶈浆鎹㈢瓑銆
class TemperatureConverter:
def __init__(self, kelvin):
self._kelvin = kelvin
@property
def kelvin(self):
return self._kelvin
@property
def celsius(self):
"""浠嶬elvin杞崲鍒癈elsius"""
return self._kelvin - 273.15
@celsius.setter
def celsius(self, value):
"""璁剧疆Celsius娓╁害 锛屽悓鏃舵洿鏂癒elvin"""
self._kelvin = value + 273.15
converter = TemperatureConverter(273.15)
print(converter.celsius) # 杈撳嚭: 0.0
converter.celsius = 100 # 璁剧疆鎽勬皬娓╁害
print(converter.kelvin) # 杈撳嚭: 373.15锛岀敱浜巗etter鏇存柊浜哶kelvin
閫氳繃杩欎簺绀轰緥鍙互鐪嬪嚭锛宲roperty瑁呴グ鍣ㄤ负灞炴ц闂彁渚涗簡浼橀泤涓斿己澶х殑鎺у埗鎵嬫锛屼娇寰椾唬鐮佹洿鍔犳暣娲併佹槗浜庣悊瑙e拰缁存姢銆
11銆佹荤粨 ??
鎺㈢储Python楂樼骇鎶鏈箣鏃咃紝鎴戜滑娣卞叆娴呭嚭鍦板墫鏋愪簡闈㈠悜瀵硅薄璁捐鍘熷垯銆佽楗板櫒搴旂敤銆佹彃浠跺寲璁捐銆佸厓绫讳笌鍔ㄦ佺被鍒涘缓銆佹弿杩扮鐨勭簿缁嗘帶鍒躲佹暟鎹被楂樻晥鍒╃敤锛屼互鍙婂苟鍙戠紪绋嬩笌灞炴х鐞嗙殑浼樺寲绛栫暐銆傛瘡绔犺妭绮惧績鏋勫缓锛屼粠鐏垫椿鏋勫缓绫荤粨鏋勫埌鑷姩鎵ц鏃ュ織涓庢ц兘鐩戞帶锛屽啀鍒板睘鎬ц闂殑浼橀泤灏佽锛屽叏鏂逛綅瑕嗙洊浜嗘彁鍗囦唬鐮佽川閲忋佸彲缁存姢鎬у拰鎵ц鏁堢巼鐨勬牳蹇冩妧宸с傛鎸囧崡鍑濊仛浜嗛潰鍚戝璞$紪绋嬬殑绮惧崕锛屽姪鍔涘紑鍙戣呭湪瀹炴垬涓父鍒冩湁浣欙紝瀹炵幇浠g爜鐨勯珮鏁堜笌浼橀泤銆
浠ヤ笂灏辨槸鎺屾彙Python 杩10涓狾OP鎶鏈紝浠g爜鎯冲啓涓嶅ソ閮介毦锛佺殑璇︾粏鍐呭锛屾洿澶氫俊鎭鍏虫敞OD浜戝叾瀹冪浉鍏虫枃绔狅紒