Object Manipulation Tricks
1. Dynamic Object Creation
## Using type() for dynamic object creation
DynamicClass = type('DynamicClass', (object,), {
'method': lambda self: print("LabEx Dynamic Method")
})
obj = DynamicClass()
obj.method() ## Outputs: LabEx Dynamic Method
Object Copying Strategies
graph TD
A[Object Copying] --> B[Shallow Copy]
A --> C[Deep Copy]
A --> D[Reference Copy]
2. Copy Methods
import copy
## Shallow vs Deep Copy
original_list = [1, [2, 3], 4]
shallow_copy = original_list.copy()
deep_copy = copy.deepcopy(original_list)
shallow_copy[1][0] = 'X' ## Modifies original list
deep_copy[1][0] = 'Y' ## Does not modify original list
Object Attribute Manipulation
3. Dynamic Attribute Management
class FlexibleObject:
def __init__(self):
self._data = {}
def __getattr__(self, name):
return self._data.get(name, None)
def __setattr__(self, name, value):
if name == '_data':
super().__setattr__(name, value)
else:
self._data[name] = value
## Dynamic attribute usage
obj = FlexibleObject()
obj.name = "LabEx"
print(obj.name) ## Outputs: LabEx
Object Introspection Techniques
Technique |
Method |
Description |
Attribute Listing |
dir() |
List all attributes |
Type Checking |
hasattr() |
Check attribute existence |
Attribute Retrieval |
getattr() |
Safely get attributes |
4. Advanced Introspection
class IntrospectionDemo:
class_var = 42
def method(self):
pass
## Introspection techniques
obj = IntrospectionDemo()
## Get all attributes
print(dir(obj))
## Check attribute existence
print(hasattr(obj, 'method'))
## Dynamically get attribute
method = getattr(obj, 'method')
Object Serialization Tricks
5. Flexible Serialization
import json
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if hasattr(obj, '__dict__'):
return obj.__dict__
return str(obj)
## Custom object serialization
class CustomObject:
def __init__(self, name):
self.name = name
obj = CustomObject("LabEx")
serialized = json.dumps(obj, cls=CustomEncoder)
print(serialized)
6. Lightweight Object Creation
from types import SimpleNamespace
## Creating lightweight objects
user = SimpleNamespace(
name="John Doe",
age=30,
email="[email protected]"
)
print(user.name) ## Outputs: John Doe
Advanced Object Comparison
7. Custom Comparison Methods
class ComparableObject:
def __init__(self, value):
self.value = value
def __eq__(self, other):
return self.value == other.value
def __lt__(self, other):
return self.value < other.value
## Custom comparison
obj1 = ComparableObject(10)
obj2 = ComparableObject(10)
obj3 = ComparableObject(20)
print(obj1 == obj2) ## True
print(obj1 < obj3) ## True
Best Practices
- Use dynamic object manipulation judiciously
- Understand memory implications
- Prefer built-in methods when possible
- Document complex object transformations
By mastering these object manipulation tricks, you'll write more flexible and powerful Python code with LabEx.