如何用类装饰器自动重赋值self.__class__以解决reload()对象类丢失问题?
Fixing Reload() Class Mismatch with a Class Decorator
Absolutely! You can automate the self.__class__ reassignment for every method in your classes using a class decorator. This way you don't have to manually add that line to each method, and it'll handle reload() scenarios seamlessly.
Here's a step-by-step implementation:
1. The Class Decorator
First, create a decorator that wraps every instance method of a class to inject the self.__class__ reassignment at the start of the method call:
import types def auto_fix_reload(cls): # Iterate over all attributes in the class namespace for attr_name, attr_value in list(cls.__dict__.items()): # Target only instance methods (skip class/static methods if needed) if isinstance(attr_value, types.FunctionType): # Define a wrapper that updates self.__class__ before running the original method def method_wrapper(self, *args, **kwargs): # Force self to use the current (reloaded) class definition self.__class__ = cls # Call the original method with updated self return attr_value(self, *args, **kwargs) # Replace the original method with our wrapped version setattr(cls, attr_name, method_wrapper) return cls
2. Applying the Decorator to Your Classes
Add the @auto_fix_reload decorator to every class in your module that needs this fix:
# mother_and_child_in_same_file.py @auto_fix_reload class Mother: def mother_method(self): print("Mother method executed") @auto_fix_reload class Child(Mother): def child_method(self): print("Child method executed")
3. How It Works
- When you reload your module, the decorator runs again on the newly loaded class definitions.
- Every instance method gets wrapped to first set
self.__class__to the current (reloaded) class. - Even instances created before the reload will now use the updated class definition whenever they call a method, because the wrapper forces the reassignment each time.
Notes
- If you need to handle class methods or static methods, you can extend the decorator to check for
classmethodorstaticmethodtypes and adjust the wrapper logic accordingly. - This approach ensures you don't have to repeat the
self.__class__line in every method, keeping your code clean and maintainable.
内容的提问来源于stack exchange,提问作者user2827908
相关产品推荐
相关产品推荐

