Programming Python, Part I

This tutorial jumps right in to the power of Python without dragging you through basic programming.
Special Methods

Having to create an object and then set each of its members is not pleasant. It takes a lot of lines and is very error-prone—did I remember to set the tags? There's a better way to do it—using the initialization method.

This special method is called __init__, and the parameters you define it to take have to be passed in the creation of the object. A possible initialization method would be:

class Post(object):
    def __init__(self, title, body):
        self.set_title(title)
        self.set_body(body)

Simply add the __init__ definition to the file and reload it. We now can, and have to, set the title and body at initialization time:

>>> cool = blog.Post("Cool", "Python is cool")
>>> cool.get_title()
'Cool'
>>> cool.get_body()
'Python is cool'
>>> 

Hint: to retrieve previous lines in the REPL inside Emacs use Alt-P.

There are other special methods. Remember how ugly it was to evaluate a Post itself? Let me remind you:


>>> cool
<blog.Post object at 0xb7c7e9ac>

We can solve that. There's another special method called __repr__, which is used to retrieve that string. Inside the Post class add:

def __repr__(self):
    return "Blog Post: %s" % self.get_title()

Reload the file, the same way you loaded it previously, and evaluate a post:


>>> ## working on region in file /usr/tmp/python...
>>> cool
<blog.Post object at 0xb7c7e9ac>
>>> 

Oops! That's not what we wanted. The problem here is that the cool object was created with an older version of the Post class, so it doesn't have the new method. That is a very common mistake, and not being prepared for it can cause a lot of headaches. But, simply re-create the object, and you are set:

>>> ## working on region in file /usr/tmp/python...
>>> cool = blog.Post("Cool", "Python is cool")
>>> cool
Blog Post: Cool
>>> 

That's better.

What Now?

Easy—wait for the next issue of Linux Journal for Part II of this tutorial. If you really want something to do now, start learning Emacs.

José P. E. “Pupeno” Fern´ndez has been programming since...at what age is a child capable of siting in a chair and reaching a keyboard? He has experimented with more languages than can be listed on this page. His Web site is at pupeno.com, and he always can be reached, unless you are a spammer, at pupeno@pupeno.com.

______________________

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

add_post function

ojo's picture

>>> def add_post(blog, new_post):
... blog = blog + [new_post]

The blog inside the function is not the same as the blog outside the function.

I think this is wrong. The blog inside the function is the same as the blog outside the function (variables behaves like references in 'C++'). The problem is in 'x = x + y' instruction. It makes new object 'x+y' and then assgin x to this new object.

So, this virsion of function 'add_blog' works fine:

>>> def add_post(blog, new_post):
... blog += [new_post]

I've changed 'blog = blog+[new_post]' to 'blog+=[new_post]'

>>> cool = blog.Post("Cool", "Python is cool")

chester's picture

produces
AttributeError: 'Post' object has no attribute 'set_title'
(Python 2.5.1c1 Ubuntu feisty)

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState