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
class. However, they won't do much because they have no methods or attributes.
We can use this newly-minted Useless
class to create objects, for what little it's worth. The following is an example:
>>> Useless() <__main__.Useless object...