Learning Python
Nov 1, 2008 at 17:00
Tom Cameron

 

I've been learning a new programming language named Python for the past week. I've been serious about it since Tuesday afternoon when I bought a book on my Kindle about it. So far, I've written some test programs, and I've started work on some changes I'd love to see implemented in SBackup.

So, one thing that's very interesting about Python is that you can have an object (everything is an object) that implements methods. If you want to call methods within an object, but you don't know what they are, you can do something VERY creative! The following code returns something very nice:


import string

methodlist = [method for method in dir(string) if callable(getattr(string,method))]

So, what are we doing here? We first import a pre-built (and deprecated) package of code called "string". From there, we declare the variable "methodlist" is to contain the results from what happens to the right of the equal sign. That code is broken down as such:

Return the contents of the variable "method" for every time we can fill "method" from the results of the items within the code "string" IF the attributes of the code deem it to be executable.

Why is this so cool? Well, first of all, it saves you time in research! More importantly, though, it can drastically simplify the code you have to write in your applications. Let's say you write a program that imports a package of code you wrote that contains several executable methods. Each of these methods is used to return some results from data you feed it.

To do this is most other languages, you need to know what methods you want to run, and you must execute them one at a time. In Python, however, you now have a list of methods, which you can loop through as above, and feed them all whatever data you want! This means you can implement in one line what would take you 30 or more just for the above example! That's a huge payoff for something so simple, and smaller programs usually execute faster with smaller memory requirements.

Anyway, I'm enjoying Python so far, and I hope to be able to contribute some good code to the SBackup community and the Ubuntu community in the future.

 

Article originally appeared on My happy place (https://www.drdabbles.us/).
See website for complete article licensing information.