Python 3类方法中实现宏:避免重复赋值成员变量
M = self.useful_member in Multiple Methods Great question! Having to write that same line in every method feels totally unnecessary—here are a few practical, clean solutions to cut down on the repetition:
1. Use a @property for Dynamic Quick Access
This is my go-to solution because it keeps the connection to self.useful_member dynamic (so if the member ever changes, your shortcut stays in sync) without any extra lines in your methods:
class ComplicatedClass(object): def __init__(self): self.useful_member = ... # Your original initialization @property def M(self): # Every time you access self.M, it returns self.useful_member return self.useful_member def method(self): # No more assignment—just use self.M directly result = self.M.calculate_something() ... def method2(self): self.M.update_value(new_data) ... def method3(self): print(f"Current value: {self.M}") ...
If you ever need to modify useful_member through self.M, you can add a setter decorator too:
@M.setter def M(self, value): self.useful_member = value
2. Bind the Shortcut Once in __init__ (For Static/Immutable Members)
If useful_member is an immutable type (like a string, number, or tuple) or you know it will never be reassigned to a new object during the instance's lifecycle, you can assign the shortcut once in the constructor:
class ComplicatedClass(object): def __init__(self): self.useful_member = ... # Bind self.M to the same object as self.useful_member self.M = self.useful_member def method(self): print(self.M) ... def method2(self): # Works for modifying mutable objects (like lists/dicts) too self.M.append(new_item) ...
⚠️ Heads up: If you ever do self.useful_member = some_new_object, self.M will still point to the original object—this only works if the reference to useful_member never changes.
3. Use a Helper Method to Wrap Logic
If your methods have a lot of logic centered around useful_member, you can abstract the assignment into a helper that runs your method's core logic:
class ComplicatedClass(object): def __init__(self): self.useful_member = ... def _with_M(self, logic): # Handle the assignment once here M = self.useful_member return logic(M) def method(self): def method_logic(M): # All your original method code goes here, using M return M.process_data() return self._with_M(method_logic) # Or use a lambda for shorter methods def method2(self): return self._with_M(lambda M: M.filter_results("active"))
This is a bit more verbose but can be useful if you want to enforce that the method only interacts with useful_member through M.
内容的提问来源于stack exchange,提问作者R S

