You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用类装饰器自动重赋值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 classmethod or staticmethod types 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:06:37