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

Unlock This Lesson

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

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Simulated Pointers With Classes

In this lesson, you’ll simulate a pointer in Python using object-oriented programming principles. You’ll create a class to track metrics for an application. You’ll use the @property decorator to access two counter values as if they were attributes.

00:00 In this video, I’ll show you how you can take advantage of object-oriented principles to mimic pointer behavior. What we want to do is create a Metrics class that will contain two counters: one for counting the number of function calls and another for counting the number of cat pictures served.

00:21 We’ll call methods in this class to increase these counters individually. First, let’s define the class. I’ll give it an __init__ method and create a dictionary to store both counters.

00:38 The dictionary type is mutable, so we can modify these counters without creating new dictionary objects. I will define two methods that can be used to get the values of the counters.

00:51 I’ll use the @property decorator so we can access this data as if it were an attribute. Now we just need a way to increment the counters. I’ll create two methods to do that, hardcoding in a += 1 so that neither counter can ever increase by more than 1 at a time.

01:13 All that’s left to do now is instantiate the class and try it out. To do that, I’ll create a name called metrics and point it to a new Metrics object.

01:25 Then I’ll call inc_cat_pictures() twice and inc_func_calls() once. Finally, I’ll print out the values of both counters using the properties.

01:40 Great! It looks like the counters worked. These methods of simulating pointers have worked all right, but they’re kind of, well, pointless, if you really think about it.

01:52 One of the biggest benefits of pointers is reduced memory usage or, at least, manual control over the memory you’re using. Python doesn’t let us do that. Instead, we have to rely on the mutability of object types just to even mimic pointer behavior. Python is a high-level scripting language.

02:14 If the code you’re writing requires pointer-level memory management, then Python might not be the right choice of language, at least not for that part of your codebase. In the next and final lesson, I’ll show you where Python really shines: when you can interface it with C.

Become a Member to join the conversation.