The __new__() method and metaclasses
The other use case for the __new__()
method as a part of a metaclass is to control how a class definition is built. This is distinct from how __new__()
controls building an immutable object, shown previously.
A metaclass builds a class. Once a class object has been built, the class object is used to build instances. The metaclass of all class definitions is type
. The type()
function is used to create class objects.
Additionally, the type()
function can be used as a function to reveal the class of an object.
The following is a silly example of building a new, nearly useless class directly with type()
as a constructor:
Useless= type("Useless",(),{})
Once we've created this class, we can create objects of this Useless ...
Get Mastering Object-oriented Python now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.