Learntofish's Blog

A blog about math, physics and computer science

Tutorial: Object Oriented Programming in Python – Part 3

Posted by Ed on December 7, 2011

This is part 3 of the tutorial on OOP in Python. The last time we talked about the __init__() method. We want to have a closer look at it:

class Fruit:
    # method
    def __init__(self, name, color, flavor):
        # set values for attributes
        self.name = name
        self.color = color
        self.flavor = flavor
        print("The", self.name, "is", self.color, "and tastes", self.flavor, end=".")

There are two things to notice:

1. The Fruit class has an __init__() method that initializes the attributes name, color and flavor. You will notice that I have not listed the attributes above the __init__() method as before. Instead, you will only find the attributes within the __init__() method. Keep in mind that in C++ and Java you have to list the attributes, in Python we don’t have to.

2. Previously, we wrote self.name = x. This means: Assign x (on the right hand side) to self.name on the left hand side where x is passed to the __init__method().
The __init__() method may look a little strange here because of the way we assign values to the attributes. In line 5 we write self.name = name. This just means: Assign name (on the right hand side) to the attribute self.name (on the left hand side), where name on the right hand side is passed to the __init__() method. It now becomes evident why we need the keyword self: whenever we write self.name we refer to the attribute name.

Save the class in a file fruit.py and run it. Then type the following in the Python-Shell:

>>> first = Fruit("strawberry", "red", "sweet")
The strawberry is red and tastes sweet.
>>> second = Fruit("lemon", "yellow", "sour")
The lemon is yellow and tastes sour.

Remember, Fruit(…) is called the constructor. When you write Fruit(“lemon”, “yellow”, “sour”) the string “lemon” is passed to the __init__() method, and the __init__() method sets:
self.name = “lemon”


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: