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.
Pet provides a
.__new__() method that creates a new instance by randomly selecting a class from a list of existing classes.
Here’s how you can use this
Pet class as a factory of pet objects. Every time you instantiate
Pet, you get a random object from a different class.
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.
Finally, note how the
.__init__() method of
Pet never runs. And that’s because
Pet.__new__() always returns objects of a different class rather than of
02:11 In the next section of the course, you’ll take a look at how to allow only a single instance of a class.
Become a Member to join the conversation.