如何将types.new_class创建的类归属到当前运行模块而非abc模块?
When you use types.new_class to create a class that inherits from abc.ABCMeta, the issue where the class ends up belonging to the abc module instead of your current module happens because the dynamic class creation process doesn't automatically set the __module__ attribute to your current module's name. The fix is straightforward—you just need to explicitly assign this attribute to the generated class.
Modified Code Example
import abc import types class Base(metaclass=abc.ABCMeta): @abc.abstractmethod def method(self, x): pass def generate_a_class(name): def method(self, x): print(f"Method received {x}") class_body = {method.__name__: method} NewClass = types.new_class( name, bases=(Base,), # Add __module__ to the namespace pointing to the current module exec_body=lambda ns: ns.update({**class_body, '__module__': __name__})) return NewClass # Test it out print(generate_a_class("Implementation")) # Outputs <class '__main__.Implementation'>
Alternative Equivalent Approach
You can also set the __module__ property right after creating the class—this works just as well:
def generate_a_class(name): def method(self, x): print(f"Method received {x}") class_body = {method.__name__: method} NewClass = types.new_class( name, bases=(Base,), exec_body=lambda ns: ns.update(class_body)) # Manually assign the module after class creation NewClass.__module__ = __name__ return NewClass
Why This Happens
When using abc.ABCMeta as the metaclass, types.new_class doesn't automatically populate the __module__ attribute with your current module's name. Instead, it falls back to using the module where the metaclass (abc) is defined. By explicitly setting __module__ to __name__ (the name of your current running module), you force the class to be associated with the correct module.
内容的提问来源于stack exchange,提问作者jabozzo

