Update docs/tech_docs/Python_programming.md

This commit is contained in:
2024-03-01 17:00:45 +00:00
parent 3d7aa6c757
commit b59a0975c2

View File

@@ -110,6 +110,201 @@ This guide should provide you with a solid understanding of Python functions, co
---
# Understanding Objects in Python: A Technical Guide
Python is an object-oriented programming language at its core, which means everything in Python is an object. This guide delves into the technical aspects of Python objects, including their creation, manipulation, and the principles that govern their interactions.
## Basics of Python Objects
In Python, objects are instances of classes, which can contain data (attributes) and functions (methods) that operate on the data. Heres how you can define a class and create an object:
```python
class MyClass:
def __init__(self, value):
self.attribute = value
def method(self):
return f"Attribute value: {self.attribute}"
# Creating an object
my_object = MyClass(10)
print(my_object.method())
```
- **Class Definition**: Use the `class` keyword followed by the class name and a colon.
- **The `__init__` Method**: Known as the constructor, it initializes the objects state.
- **Attributes and Methods**: Attributes store the object's state, and methods define its behavior.
## Object Attributes and Methods
### Instance Attributes vs. Class Attributes
- **Instance Attributes**: Defined within methods and prefixed with `self`, unique to each object.
- **Class Attributes**: Defined outside of methods and are shared across all instances of the class.
### Instance Methods, Class Methods, and Static Methods
- **Instance Methods**: Operate on an instance of the class and have access to `self`.
- **Class Methods**: Operate on the class itself, rather than instance, and take `cls` as the first parameter. Use the `@classmethod` decorator.
- **Static Methods**: Do not access the class or its instances and are defined using the `@staticmethod` decorator.
```python
class MyClass:
class_attribute = "Shared"
def __init__(self, value):
self.instance_attribute = value
def instance_method(self):
return self.instance_attribute
@classmethod
def class_method(cls):
return cls.class_attribute
@staticmethod
def static_method():
return 'Static method called'
```
## Inheritance and Polymorphism
Inheritance allows one class to inherit the attributes and methods of another, enabling code reuse and the creation of complex object hierarchies.
```python
class BaseClass:
pass
class DerivedClass(BaseClass):
pass
```
Polymorphism allows objects of different classes to be treated as objects of a common superclass, particularly when they share a method name but implement it differently.
```python
def common_interface(obj):
obj.method_name()
```
## Magic Methods
Magic methods (or dunder methods) are special methods with double underscores at the beginning and end of their names. They enable operator overloading and custom behavior for built-in operations.
```python
class MyClass:
def __init__(self, value):
self.value = value
def __str__(self):
return f"MyClass with value: {self.value}"
```
## Encapsulation and Abstraction
- **Encapsulation**: The bundling of data with the methods that operate on that data.
- **Abstraction**: Hiding the internal implementation details of a class and exposing only the necessary parts.
## Conclusion
Understanding the technical aspects of Python objects is crucial for mastering object-oriented programming in Python. By grasping concepts like inheritance, polymorphism, and magic methods, you can design robust and reusable code structures.
---
# Mastering List Comprehensions in Python
List comprehensions in Python provide a concise way to create lists. They consist of brackets containing an expression followed by a `for` clause, then zero or more `for` or `if` clauses. This guide will explore the syntax and capabilities of list comprehensions, helping you write more Pythonic code.
## Basic Syntax
The basic syntax of a list comprehension is:
```python
[expression for item in iterable]
```
- **expression**: An expression producing a value to be included in the new list.
- **item**: The variable representing each element in the iterable.
- **iterable**: A sequence (list, tuple, string, etc.) or collection (set, dictionary, etc.) that can be iterated over.
### Example: Squaring Numbers
```python
squares = [x**2 for x in range(10)]
print(squares)
```
This creates a list of the squares of numbers 0 through 9.
## Adding Conditionals
List comprehensions can also include conditional statements to filter items from the input iterable.
### Filtering Items
```python
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares)
```
This generates a list of squares for even numbers only.
### Conditional Expressions
You can also use conditional expressions within the expression part of the list comprehension:
```python
values = [x if x > 0 else -x for x in range(-5, 5)]
print(values)
```
This creates a list where negative numbers are made positive.
## Nested List Comprehensions
List comprehensions can be nested to create complex lists:
```python
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [elem for row in matrix for elem in row]
print(flattened)
```
This flattens a list of lists into a single list.
## Using List Comprehensions with Other Data Types
While they're called list comprehensions, this syntax can be used to create sets and dictionaries as well.
### Set Comprehensions
```python
square_set = {x**2 for x in range(-5, 5)}
print(square_set)
```
This creates a set of squared numbers, removing duplicates.
### Dictionary Comprehensions
```python
square_dict = {x: x**2 for x in range(5)}
print(square_dict)
```
This creates a dictionary with numbers as keys and their squares as values.
## Best Practices
- **Readability**: Use list comprehensions for simple expressions and operations. For complex logic, consider using regular loops.
- **Performance**: List comprehensions can be faster than equivalent `for` loops, but readability should not be sacrificed for slight performance gains.
- **Avoid Side Effects**: Do not use list comprehensions for operations that have side effects, such as file I/O or modifying external variables.
## Conclusion
List comprehensions are a powerful feature of Python that allow for clean, readable, and efficient code. By understanding and applying the concepts outlined in this guide, you can leverage list comprehensions to simplify your code while maintaining or even improving its performance.
---
# Python Dictionaries: A Guide for API Calls
Python dictionaries are essential for handling data in Python, especially when working with API calls. This guide provides a concise overview of dictionaries and their use in constructing API payloads.