同一类子类多变量赋值及Python类似VB With构造咨询,征标题建议
With Block & Better Title Suggestions Recommended Title Options
Here are some clear, Stack Overflow-friendly titles that will help other developers quickly grasp your question:
- "Is there a Python equivalent to Visual Basic's 'With' block for setting multiple properties on nested objects?"
- "How to batch-assign attributes to a nested object in Python like VB's With statement?"
- "Python alternative to VB's 'With' for setting multiple properties on a returned object?"
Python's Alternatives to VB's With
Python doesn’t have a direct built-in construct identical to VB’s With block (note: Python’s own with keyword is for context management—like handling files or locks—and works completely differently). But there are several clean, idiomatic ways to achieve the same goal of setting multiple attributes on a nested object:
1. Assign the Nested Object to a Temporary Variable (Most Common & Recommended)
This is the simplest and most readable approach—just grab a reference to the nested object once, then set its properties:
# Get a reference to the nested object first target_obj = Foo_Object.Foo_method() target_obj.Bar_var1 = 'foo' target_obj.Bar_var2 = 'bar'
Python developers prefer this because it’s explicit—there’s no ambiguity about which object you’re modifying, and it’s easy to follow at a glance.
2. Use Chained Setters (If the Class Supports It)
If the object returned by Foo_method() has setter methods that return self, you can chain the calls to mimic the concise feel of VB’s With:
# Only works if the class defines setters that return the object itself Foo_Object.Foo_method()\ .set_bar_var1('foo')\ .set_bar_var2('bar')
Keep in mind this depends on how the class is designed—many Python classes don’t implement this pattern by default.
3. Batch Assignment with setattr (For Dynamic/Many Attributes)
If you have a lot of attributes to set, or if attribute names are dynamic, use Python’s built-in setattr() function with a dictionary:
target_obj = Foo_Object.Foo_method() attr_values = { 'Bar_var1': 'foo', 'Bar_var2': 'bar', # Add more attributes here if needed } for attr_name, value in attr_values.items(): setattr(target_obj, attr_name, value)
This is perfect for scaling up when you need to set dozens of attributes, or when you’re pulling attribute names/values from an external source.
内容的提问来源于stack exchange,提问作者oneindelijk

