Functions: Variables, References, and Scope (Part 1)
One of the most useful functions that I found during my time using Python is
dir(), for directory. This allows you to see all of the attributes and methods that any Python object has. This may seem a rather abstract concept, but it allows you to understand what you can do with any object.
00:59 You may have forgotten what methods are available to you, and if you’re not using something like bpython, they may not be pointed out to you. Now, while this may not give you the full documentation on the methods or attributes that are available, it can jog your memory or allow you to search for the right term.
So here, using
dir(a) we can see we get all of these methods and attributes which are available for a string. Some of these may be immediately apparent, some of them won’t, but they’re all things that you can examine in more detail or do a targeted search, or experiment with them and see what happens.
It’s a really important part of learning to understand things in your own terms. Often, other people’s explanations may not really hit the mark, and if you’ve experimented with it and understand it in the way that you need to, then you’ll know what to do with an object and be able to use it most efficiently. So here, we’ve discovered the method
a.center() and if we put in
50, we can see that it’s centered the
hello string within a 50-character gap, which can be really useful when trying to produce headings et cetera, and it’s exactly the kind of thing that I replicated myself in code which worked out how long the text was and how long the spaces were, and it took me many lines to do what
.center() could do in a single method.
This works for any kind of object in Python, so this is hugely useful and really important. No matter what kind of objects you’re dealing with, you can perform
dir() on it and see what kind of methods and attributes it has.
I happen to know that
datetime.datetime has some useful things in there, so we can do
dir(datetime.datetime), and in there there’s a list of functions and attributes which we can experiment with or search for to know exactly what we’re dealing with.
The slightly intimidating part of this is all of these what are often called dunder methods, with a double underscore (
__), and these are generally part of the internal working or initialization of objects.
03:20 But for the time being, being able to find out what kind of things an object supports—or even if an object is what you think it is—can be really useful, and then you can look into experimenting with them to improve your understanding of what’s going on and what you can do with an object.
Become a Member to join the conversation.