Returning Instances of a Different Class
Returning Instances of a Different Class. Returning an object of a different class is a requirement that can raise the need for a custom implementation of
.__new__(). However, you should be careful because in this case, Python skips the initialization step entirely.
So, you’ll have the responsibility of taking the newly created object into a valid state before using it in your code. On-screen, you’ll see an example where the
Pet class uses
.__new__() to return instances of randomly selected classes.
This result is possible because there’s no restriction on the object that
.__new__() can return. Using
.__new__() in such a way transforms a class into a flexible and powerful factory of objects, not limited to instances of itself.
Become a Member to join the conversation.