Returning Instances of a Different Class
00:01
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.
00:17
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.
00:37
Here, Pet
provides a .__new__()
method that creates a new instance by randomly selecting a class from a list of existing classes.
01:26
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.
01:40
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.
01:55
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 Pet
itself.
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.