Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Using Classes as an Alternative to Closures

00:00 In this final lesson, you’re going to look back at an example you’ve seen earlier in this course, the make_root_calculator() example. You can create a script called using_classes.py with the code you had in the previous example.

00:15 Often in Python, there’s more than one solution for the same problem, and therefore there are often alternatives to using closures. So let’s have a look at an alternative to using these nested functions that create a closure.

00:28 You can get rid of them and instead you can define a class called RootCalculator,

00:35 and you can define its __init__() method

00:39 with one parameter, which is the root degree, similar to the parameter you used in the function version earlier. However, an instance of a class always has access to all of the data attributes.

00:53 Therefore, you can create a data attribute called .root_degree.

01:00 So when we’re using classes, we don’t need to use closures since the object will always have access to all of the attributes. In the previous example, you were creating functions whereas here you have a class.

01:13 However, since Python is a duck typing language, what really matters is not that you have a function, but that you have a callable. So you can make an instance of the RootCalculator class callable by defining the __call__() method.

01:28 This special method makes every instance of the class callable and you can add the number parameter. This method defines what happens when you call an instance of a class.

01:40 In this case, you’d like to return the same calculation you had earlier: pow(number, and you raise it to the power of one divided by, but this time it’s 1 / self.root_degree).

01:56 This __call__() method is similar to the inner function you had earlier. Now you can create instances of RootCalculator. Since you no longer have the make_root_calculator() function, but instead you have the RootCalculator class, all you need to do is replace the calls to RootCalculator calls.

02:18 And cube_root is another instance of RootCalculator with .root_degree equal to 3.

02:26 You can try this out by running the script, which in my case I called using_classes.py. And as you can see, the outputs are identical to the previous version.

02:37 So instead of using a function with a closure, you could use a class to achieve exactly the same purpose. The __call__() method serves the same purpose as the inner function you had earlier, and since .root_degree is a data attribute, it’s accessible directly through __call__().

Become a Member to join the conversation.