Python:动态创建 class,同时向 __init__subclass__() 提供参数
Python: Dynamically create class while providing arguments to __init__subclass__()
如何动态创建 class 的子 class 并为其 __init_subclass__()
方法提供参数?
示例class:
class MyClass:
def __init_subclass__(cls, my_name):
print(f"Subclass created and my name is {my_name}")
通常我会这样实现我的子class:
class MySubclass(MyClass, my_name="Ellis"):
pass
但是,当使用元class 动态创建MyClass
的子class 时,我如何传入my_name
?通常我可以使用 type()
但它没有提供 my_name
.
的选项
MyDynamicSubclass = type("MyDynamicSubclass", (MyClass,), {})
type
does not mention that it accepts an unlimited number of keyword-only arguments, which you would supply through the keywords in a class
statement. The only place this is hinted in is in the Data Model in the section Creating the class object 的基本文档:
Once the class namespace has been populated by executing the class body, the class object is created by calling metaclass(name, bases, namespace, **kwds)
(the additional keywords passed here are the same as those passed to __prepare__
).
通常,您不会将此功能与 type
一起使用,正是因为 __init_subclass__
:
The default implementation object.__init_subclass__
does nothing, but raises an error if it is called with any arguments.
由于您已经覆盖了默认实现,您可以将动态 class 创建为
MyDynamicSubclass = type("MyDynamicSubclass", (MyClass,), {}, my_name="Ellis")
如何动态创建 class 的子 class 并为其 __init_subclass__()
方法提供参数?
示例class:
class MyClass:
def __init_subclass__(cls, my_name):
print(f"Subclass created and my name is {my_name}")
通常我会这样实现我的子class:
class MySubclass(MyClass, my_name="Ellis"):
pass
但是,当使用元class 动态创建MyClass
的子class 时,我如何传入my_name
?通常我可以使用 type()
但它没有提供 my_name
.
MyDynamicSubclass = type("MyDynamicSubclass", (MyClass,), {})
type
does not mention that it accepts an unlimited number of keyword-only arguments, which you would supply through the keywords in a class
statement. The only place this is hinted in is in the Data Model in the section Creating the class object 的基本文档:
Once the class namespace has been populated by executing the class body, the class object is created by calling
metaclass(name, bases, namespace, **kwds)
(the additional keywords passed here are the same as those passed to__prepare__
).
通常,您不会将此功能与 type
一起使用,正是因为 __init_subclass__
:
The default implementation
object.__init_subclass__
does nothing, but raises an error if it is called with any arguments.
由于您已经覆盖了默认实现,您可以将动态 class 创建为
MyDynamicSubclass = type("MyDynamicSubclass", (MyClass,), {}, my_name="Ellis")