How can I dynamically create a subclass of my class and provide arguments to its __init_subclass__()
method?
Example class:
class MyClass:
def __init_subclass__(cls, my_name):
print(f"Subclass created and my name is {my_name}")
Normally I'd implement my subclass as such:
class MySubclass(MyClass, my_name="Ellis"):
pass
But how would I pass in my_name
when dynamically creating a subclass of MyClass
using a metaclass? Normally I could use type()
but it doesn't have the option of providing my_name
.
MyDynamicSubclass = type("MyDynamicSubclass", (MyClass,), {})
type
is a metaclass. If you want to use a different metaclass, call that instead. The interface should be similar. – Collodiontype
doesn't receive the argument. You would have to manually call it after the creation – ShaylynnMyDynamicSubclass.__init_subclass__(my_name="Ellis")
? – Mathenytype
at the end of the argument list? The documentation implies that it's worth trying :) – CollodionMyDynamicSubclass = type("MyDynamicSubclass", (MyClass,), {}, my_name='Ellis')
– Collodion