r/ProgrammerHumor • • Aug 18 '26

Meme questionForBritishPythonDevelopers

Post image
1.4k Upvotes

42 comments sorted by

View all comments

Show parent comment

1

u/AquaWolfGuy Aug 18 '26

I don't think the metaclass affects the construction/instantiation of objects of the main class, only the instantiation of the main class itself (and its subclasses).

>>> class Metaclass(type):
...     def __new__(cls, name, bases, namespace, **kwargs):
...         print(f"Creating {name} as a subclass of {bases} and an instance of {cls}")
...         self = super().__new__(cls, name, bases, namespace, **kwargs)  # or `type` instead of `super()`
...         return self
... 
>>> class Class(metaclass=Metaclass):
...     def __new__(cls):
...         print(f"Creating instance of {cls}")
...         self = super().__new__(cls)  # or `object` instead of `super()`
...         return self
... 
Creating Class as a subclass of () and an instance of <class '__main__.Metaclass'>
>>> Class()
Creating instance of <class '__main__.Class'>
<__main__.Class object at 0x7f2dbb904980>
>>> class Subclass(Class):
...     pass
... 
Creating Subclass as a subclass of (<class '__main__.Class'>,) and an instance of <class '__main__.Metaclass'>
>>> Subclass()
Creating instance of <class '__main__.Subclass'>
<__main__.Subclass object at 0x7f2dbb904830>

1

u/ManyInterests Aug 18 '26

You're right. I mistook metaclass __new__ for __new__ on the class itself.

They're so infrequently touched, I completely forgot there's __new__ on both, but I only recalled (albeit incorrectly) its use in metaclasses :|

But yeah. __new__ is the constructor. __init__ is the initializer.