Learntofish's Blog

A blog about math, physics and computer science

Tutorial: Object Oriented Programming in Python – Part 1

Posted by Ed on December 4, 2011

I wrote a tutorial on Object Oriented Programming (OOP) using Java. Here, I want to give you a 10 part tutorial on OOP in Python. Note:
– I use Python 3.2.2. If you use Python 2.7 there may be some issue with the print command.
– I will assume that you have installed IDLE, the Python IDE.

To run a file in IDLE proceed as follows:
1) Starting IDLE:
In Windows go to:
Start -> all programs -> Python 2.7 -> IDLE (Python GUI) or
Start -> all programs -> Python 3.2 -> IDLE (Python GUI)

2) Opening the file in IDLE:
After starting IDLE click on: File -> Open
Navigate to the file. Double click on it.

3) After double-clicking on the file a new window opens that shows the code.
Run it by clicking on: Run -> Run Module
(or just simply press F5)

Those who wish to work without IDLE can run a file in the interpreter by typing the following in a console (terminal):
python -i myFileName.py

The other parts can be found here:
Part 2 – The __init__() method
Part 3 – More on the __init__() method
Part 4 – A simple Vehicle class
Part 5 – Inheritance
Part 6 – Modules
Part 7 – if __name__ == “__main__”
Part 8 – Call by value and reference
Part 9 – Private variables and methods
Part 10 – Installing PyDev (Python in Eclipse)

What is an object?
Definition: An object in Object Oriented Programming is characterized by
a) its attributes (properties)
b) methods that do something with the attributes (for example change them)

What is a class?
There are different kind of objects, for example:
– Marie Curie, Isaac Newton and Emmy Noether have something in common. They are persons. We say that they are objects of the class “Person”.
– Apple, banana, mango: These are objects of the class “Fruit”.
– Jacket, blouse, pullover, pants: These are objects of the class “Clothes”.

Example:
Below you see an example for a Person class in Python. Copy the Python code and save it in a file person.py.

class Person:
    # attributes (properties)
    name = "No name yet"
    age = 0

    # methods
    def setName(self, x):
        self.name = x

    def setAge(self, x):
        self.age = x

    def talk(self):
        print("Hi! My name is", self.name, "and I am", self.age, "years old.")

Notice that the class describes the two things defining an object:
Firstly, its attributes and secondly its methods.

After copying the code execute the file person.py. In IDLE just go to Run -> Run Module (or simply press F5). We will now work in the Python Shell. Type the following:

>>> myObject = Person()
>>> myObject.setName("Peter")
>>> myObject.setAge(22)
>>> myObject.talk()
Hi! My name is Peter and I am 22 years old.

In line 1 you have created an object myObject. Notice that you have used the so-called constructor Person() which creates an object and assigns it to the variable myObject. In line 2 and 3 you have set the name and age respectively. In line 4 you make the object talk.

We can create as many objects as we like. Let’s just create another one by typing the following in the Python Shell:

>>> someObject = Person()
>>> someObject.setName("Sandra")
>>> someObject.setAge(35)
>>> someObject.talk()
Hi! My name is Sandra and I am 35 years old.

Exercise 1:
Create another object of the class Person using the Python-Shell. Choose “Charlie Brown” as name and 8 as age. Let the object talk.

Exercise 2:
a) Write a class Car. The Car class shall contain the attributes brand and maxSpeed, and the methods setBrand(), setMaxSpeed() and printData().
b) Create a Car object, e.g. an Audi with maxSpeed 200 km/h. Create a second object.

Solution to exercise 1:
Type the following in the Python-Shell:

>>> obj = Person()
>>> obj.setName("Charlie Brown")
>>> obj.setAge(8)
>>> obj.talk()
Hi! My name is Charlie Brown and I am 8 years old.

Solution to exercise 2:
a) Below is the Car class:

class Car:
    # attributes
    brand = "No brand yet"
    maxSpeed = 0

    # methods
    def setBrand(self,x):
        self.brand = x

    def setMaxSpeed(self,x):
        self.maxSpeed = x

    def printData(self):
        print("The car was manufactured by", self.brand, ",")
        print("and its maximum speed is", self.maxSpeed, "km/h.")

b) Type the following in the Python-Shell:

>>> c1 = Car()
>>> c1.setBrand("Audi")
>>> c1.setMaxSpeed(200)
>>> c1.printData()
The car was manufactured by Audi ,
and its maximum speed is 200 km/h.
>>> c2 = Car()
>>> c2.setBrand("BMW")
>>> c2.setMaxSpeed(180)
>>> c2.printData()
The car was manufactured by BMW ,
and its maximum speed is 180 km/h.

References:
Python documentation

Advertisements

7 Responses to “Tutorial: Object Oriented Programming in Python – Part 1”

  1. […] This is a great introductory series to object-oriented programming (oop) for Python. There’s also one for Java. […]

  2. […] Tutorial: Object Oriented Programming in Python – from Learntofish’s Blog. […]

  3. Umar said

    Even though, this post was made long ago, I will say it is helpful reading it after 4years. Thank

  4. Prateek said

    Nice post. i also wrote some tutorials at http://thepythonguru.com/python-object-and-classes/

  5. stato said

    Also recommend these:
    http://pythonspot.com/
    http://www.stavros.io/tutorials/python/

  6. stato said

    Also recommend these:
    https://pythonspot.com
    http://www.stavros.io/tutorials/python/

  7. […] stato on Tutorial: Object Oriented Prog… […]

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: