After crashing with metaclasses i delved into the topic of metaprogramming in Python and I have a couple of questions that are, imho, not clearly anwered in available docs.
- When using both
__new__and__init__in a metaclass, their arguments must be defined the same? - What’s most efficient way to define class
__init__in a metaclass? - Is there any way to refer to class instance (normally self) in a metaclass?
For 1: The
__init__and__new__of any class have to accept the same arguments, because they would be called with the same arguments. It’s common for__new__to take more arguments that it ignores (e.g.object.__new__takes any arguments and it ignores them) so that__new__doesn’t have to be overridden during inheritance, but you usually only do that when you have no__new__at all.This isn’t a problem here, because as it was stated, metaclasses are always called with the same set of arguments always so you can’t run into trouble. With the arguments at least. But if you’re modifying the arguments that are passed to the parent class, you need to modify them in both.
For 2: You usually don’t define the class
__init__in a metaclass. You can write a wrapper and replace the__init__of the class in either__new__or__init__of the metaclass, or you can redefine the__call__on the metaclass. The former would act weirdly if you use inheritance.And the result from calling it:
For 3: Yes, from
__call__as shown above.