### Data Structures - **Lists:** Ordered, mutable, allows duplicates. `[1, 'a', 2]` - **Tuples:** Ordered, immutable, allows duplicates. `(1, 'a', 2)` - **Dictionaries:** Unordered, mutable, key-value pairs. `{'key': 'value'}` - **Sets:** Unordered, mutable, unique elements. `{1, 2, 3}` #### List Comprehensions - Concise way to create lists. ```python squares = [x**2 for x in range(10) if x % 2 == 0] # [0, 4, 16, 36, 64] ``` #### Dictionary Comprehensions - Similar to list comprehensions. ```python sq_dict = {x: x**2 for x in range(5)} # {0:0, 1:1, 2:4, 3:9, 4:16} ``` ### Functions & Decorators #### Function Definition ```python def greet(name="World"): """Greets the given name.""" return f"Hello, {name}!" ``` #### Lambda Functions - Small, anonymous functions. ```python add = lambda x, y: x + y print(add(5, 3)) # 8 ``` #### Decorators - Functions that modify other functions. ```python def my_decorator(func): def wrapper(*args, **kwargs): print("Something is happening before the function is called.") result = func(*args, **kwargs) print("Something is happening after the function is called.") return result return wrapper @my_decorator def say_hello(): print("Hello!") say_hello() ``` ### Object-Oriented Programming (OOP) #### Classes & Objects ```python class Dog: # Class attribute species = "Canis familiaris" def __init__(self, name, age): self.name = name # Instance attribute self.age = age def bark(self): return f"{self.name} says Woof!" my_dog = Dog("Buddy", 3) print(my_dog.bark()) ``` #### Inheritance ```python class GoldenRetriever(Dog): def __init__(self, name, age, color): super().__init__(name, age) # Call parent constructor self.color = color def fetch(self): return f"{self.name} fetches the ball." golden = GoldenRetriever("Goldie", 2, "golden") print(golden.fetch()) print(golden.bark()) ``` #### Encapsulation - Using `_` for protected and `__` for private attributes (by convention/name mangling). ```python class MyClass: def __init__(self): self._protected_var = 10 # Convention for protected self.__private_var = 20 # Name mangling for pseudo-private ``` ### Error Handling ```python try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero!") except TypeError as e: print(f"Type error: {e}") else: print("Operation successful!") finally: print("This always executes.") ``` ### Generators & Iterators #### Generators - Functions that return an iterator. Use `yield`. ```python def count_up_to(n): i = 0 while i ### Asynchronous I/O #### `async` and `await` - For concurrent programming. ```python import asyncio async def fetch_data(delay): print(f"Fetching data... (delay: {delay})") await asyncio.sleep(delay) print(f"Data fetched! (delay: {delay})") return f"Result from {delay}s wait" async def main(): task1 = asyncio.create_task(fetch_data(2)) task2 = asyncio.create_task(fetch_data(1)) results = await asyncio.gather(task1, task2) print(f"All tasks completed: {results}") if __name__ == "__main__": asyncio.run(main()) ``` ### Design Patterns #### Singleton Pattern - Ensures a class has only one instance. ```python class Singleton: _instance = None def __new__(cls): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance s1 = Singleton() s2 = Singleton() print(s1 is s2) # True ``` #### Factory Method - Creates objects without specifying the exact class. ```python class Dog: def speak(self): return "Woof!" class Cat: def speak(self): return "Meow!" def animal_factory(animal_type): if animal_type == "dog": return Dog() elif animal_type == "cat": return Cat() else: raise ValueError("Unknown animal type") my_animal = animal_factory("dog") print(my_animal.speak()) ``` ### 3D Models (Conceptual) Please note: Direct 3D model rendering within a cheatsheet is not supported. This section conceptually illustrates Python's role in 3D. #### Blender Python API - Automate tasks, create geometry, render scenes. ```python # Example: Create a cube in Blender import bpy bpy.ops.mesh.primitive_cube_add(size=2, enter_editmode=False, align='WORLD', location=(0, 0, 0)) ``` #### Libraries for 3D Graphics - **PyOpenGL:** Python bindings for OpenGL. - **Panda3D:** Game engine, powerful 3D rendering. - **Open3D:** For 3D data processing (point clouds, meshes). *Image represents a conceptual 3D model, illustrating Python's use in generating or manipulating such models through libraries like Blender, PyOpenGL, or Open3D. (Image URL is a placeholder as direct 3D models are not supported).*