[Tutor] __new__ and __init__

Steven D'Aprano steve at pearwood.info
Wed Aug 1 17:53:46 CEST 2012


On 02/08/12 01:10, Hugo Arts wrote:

> * small caveat: I'm entirely unsure of this, but I *think* if you create
> CarModel with a metaclass that overrides __call__ you can change the way
> __new__ and __init__ work? If anyone can confirm this, be my guest.

Correct. Metaclasses can essentially change *nearly* everything about how 
classes and instances are created.



py> class MyMeta(type):
...     def __call__(self, *args):
...             instance = self.__new__(self, "magic")
...             instance.__init__("happens")
...             instance.colour = "sparkly"
...             return instance
...
py>
py> class MyClass(object, metaclass=MyMeta):
...     def __new__(cls, arg):
...             print("received argument", arg)
...             return super().__new__(cls, arg)
...     def __init__(self, arg):
...             print("received argument", arg)
...             self.arg = arg
...
py>
py> inst = MyClass("these", "args", "are", "ignored")
received argument magic
received argument happens
py> inst.colour
'sparkly'




-- 
Steven


More information about the Tutor mailing list