Creating New Instances With __new__
00:00
Creating New Instances with the __new__
Magic Method When you call a class constructor to create a new instance of a class, Python implicitly calls the __new__
magic method as the first step in the instantiation process.
00:17
So in your dog example, when you create the Buddy and Lucy instances, Python first calls the __new__
magic method. This method is responsible for creating and returning a new empty Dog object.
00:33
Once that new object is created, Python then passes it to the .__init__()
method for initialization, setting the name and age, as you’ve seen with Buddy and Lucy.
00:44
That’s it. So far you haven’t needed to modify the __new__
method, but sometimes it can be really useful. For example, when you’re working with immutable types like integers, floats, tuples, and strings, you might want to customize how these objects are created.
01:04
This is where a custom implementation of the __new__
magic method comes in handy.
01:11
Let’s create a Storage
class that’s derived from float
and also stores a unit of measure like gigabytes or megabytes.
01:22
Let’s start by defining the class. You’re creating a Storage
class that inherits from the float
class. This means Storage
will have all the behavior of a float
, but you can add more to it.
01:35
class Storage(float):
The __new__
method is where Python creates a new instance of the class and where you need to modify the float
class.
01:48
For that, you need to pass cls
, which is the Storage
class itself, value
, which is the numeric value, and unit
like gigabytes or megabytes as arguments.
02:01
Now you need to call the super()
function on the __new__
magic method to let Python create a new float
object using the value.
02:10
This instance is now your basic Storage
object, which is really just a float
with some extra potential. So super().__new__(
02:28
Now you need to add the .unit
attribute to your Storage
instance. This makes your Storage
object special. It has a numeric value and a unit of measurement. instance
.unit = unit
and let’s just add instance.value = value
as well because you’ll need it later.
02:53
Finally, you just need to return the customized Storage
instance. It’s now ready to be used with both the value and the unit. Now let’s create a storage size of 512 gigabytes.
03:07
storage_size = Storage(512
, "GB")
or gigabyte as the unit.
03:19
Let’s run this program and see what happens when you print(storage_size)
.
03:30 You get 512. You have successfully created an instance for your new customized class, but you might notice that you don’t really have a decent string representation for this class right now, as you can only see the value and not the unit.
03:48 How to fix this is exactly what you’ll learn in the next lesson.
Become a Member to join the conversation.