square = Square(10) print(f"Square Area: {square.area()}") print(f"Square Perimeter: {square.perimeter()}") except TypeError as e: print(f"\nError trying to instantiate Square: {e}")
# Output (假设 Square 已正确实现所有方法): # Circle Area: 78.53975 # Circle Perimeter: 31.4159 # Circle Description: This is a generic shape. # Square Area: 100 # Square Perimeter: 40
@config_name.setter defconfig_name(self, value: str): ifnotisinstance(value, str): raise ValueError("Config name must be a string") self._config_name = value
service = MyService("UserAuthentication") print(f"Service config name: {service.config_name}") service.config_name = "AuthServiceV2" print(f"Updated service config name: {service.config_name}")
@classmethod def__subclasshook__(cls, C): if cls is CustomContainer: # 只对 CustomContainer 本身进行检查 # 检查 C 是否有 'add' 方法,并且实现了 __len__ 魔术方法 # 这里只是简单检查,实际情况可能需要更复杂的逻辑 ifany("add"in B.__dict__ for B in C.__mro__) and \ any("__len__"in B.__dict__ for B in C.__mro__): returnTrue returnNotImplemented
# MyList 没有显式继承 CustomContainer print(f"MyList is a subclass of CustomContainer: {issubclass(MyList, CustomContainer)}") # Output: MyList is a subclass of CustomContainer: True (因为它符合 __subclasshook__ 的定义) print(f"MyList is an instance of CustomContainer: {isinstance(MyList(), CustomContainer)}") # Output: MyList is an instance of CustomContainer: True
三、使用场景与优势
3.1 明确定义接口
在构建大型库或框架时,ABC 是定义清晰 API 的利器。例如,设计一个可以接收不同类型数据存储的组件时:
defconnect(self): print(f"Connecting to file storage: {self.filepath}") self.file_handle = open(self.filepath, 'a+') # Use append and read mode # Simulate connecting
defdisconnect(self): ifself.file_handle: self.file_handle.close() print(f"Disconnected from file storage: {self.filepath}")
defread_data(self, key: str) -> str: ifnotself.file_handle: raise RuntimeError("Not connected to file storage.") # Simplified read: search for key on each line (not efficient for large files) self.file_handle.seek(0) # Go to beginning of file for line inself.file_handle: if line.startswith(key + ":"): return line[len(key) + 1:].strip() return""# Key not found
defwrite_data(self, key: str, value: str): ifnotself.file_handle: raise RuntimeError("Not connected to file storage.") self.file_handle.write(f"{key}:{value}\n") print(f"Wrote '{key}:{value}' to {self.filepath}")
defconnect(self): print(f"Connecting to database with config: {self.db_config}") # Simulate DB connection self.db_connection = "DB_Connection_Object"
defdisconnect(self): ifself.db_connection: print("Disconnected from database.") self.db_connection = None
defread_data(self, key: str) -> str: ifnotself.db_connection: raise RuntimeError("Not connected to database.") print(f"Reading data for key '{key}' from database.") returnf"Value_from_DB_for_{key}"# Placeholder
defwrite_data(self, key: str, value: str): ifnotself.db_connection: raise RuntimeError("Not connected to database.") print(f"Writing data for key '{key}' with value '{value}' to database.")