Python Object Oriented - Python Programming by Example (2015)

Python Programming by Example (2015)

5. Python Object Oriented

This chapter we explore how to work with Object-Oriented programming in Python.

5.1 Creating Classes

Object-oriented programming (OOP) is a programming language model organized around objects. In this chapter, I don’t explain in detail about OOP. I recommend you to read textbooks related to OOP.

In OOP, a class is a template definition of the method s and variable s in a particular kind of object. You can declare a class in Python as follows.

from math import *

class City:

# class data

city_count = 0

city_id = 0

### do something

Note: You can work with OOP using Python 3.x.

After declared a class, we can use it.

a = City()

b = City()

5.2 Class Attributes

We can declare class attributes to store the data or to communicate to other object.

For instance, we declare city_count and city_id. We also define methods: move_to() and distance().

class City:

# class data

city_count = 0

city_id = 0

# class attributes

def move_to(self, x=0, y=0):

self.x += x

self.y += y

def distance(self, other_city):

xi = pow(other_city.x - self.x, 2)

yi = pow(other_city.y - self.y, 2)

return sqrt(xi + yi)

5.3 Built-In Class Attributes

Basically, Python has built-in class attributes, such as __init__() is used as class contructor and __str__() to generate information about the class.

class City:

# class data

city_count = 0

city_id = 0

# constructor

def __init__(self, name='', x=0, y=0):

self.name = name

self.x = x

self.y = y

City.city_count += 1 # access all City classes

self.city_id = City.city_count

def __str__(self):

return 'City: ' + self.name + ',id=' + str(self.city_id) + ',x=' + str(self.x) + ',y=' + str(self.y)

5.4 Destroying Class Object

In a class, we can define destructor to clear all usage resouces. We can use __del__() in Python to do that.

class City:

def __del__(self):

# get class name

class_name = self.__class__.__name__

print('class ', class_name, ' destroyed')

5.5 Write them All

Let's try to write the code in implementation. Create a file, called ch05_01.py, and write these scripts.

from math import *

class City:

# class data

city_count = 0

city_id = 0

# constructor

def __init__(self, name='', x=0, y=0):

self.name = name

self.x = x

self.y = y

City.city_count += 1 # access all City classes

self.city_id = City.city_count

def __str__(self):

return 'City: ' + self.name + ',id=' + str(self.city_id) + ',x=' + str(self.x) + ',y=' + str(self.y)

# class attributes

def move_to(self, x=0, y=0):

self.x += x

self.y += y

def distance(self, other_city):

xi = pow(other_city.x - self.x, 2)

yi = pow(other_city.y - self.y, 2)

return sqrt(xi + yi)

def __del__(self):

# get class name

class_name = self.__class__.__name__

print('class ', class_name, ' destroyed')

a = City('Hamburg', 10, 5)

b = City('Berlin', 3, 10)

print(a)

print(b)

print(City.city_count)

a.move_to(4, 3)

b.move_to(7, 12)

print(a)

print(b)

distance = a.distance(b)

print(distance)

Now you can run the program.

$ python3 ch05_01.py

A sample of program output:

p5-1

5.6 Inheritance

Inheritance, encapsulation, abstraction, and polymorphism are four fundamental concepts of object-oriented programming. In this section, we implement inheritance in Python.

Inheritance enables new objects to take on the properties of existing objects. A class that is used as the basis for inheritance is called a superclass or base class. In Python, we can declare inheritance as follows.

import math

class shape:

def __init__(self):

print('call __init__ from shape class')

def foo(self):

print('calling foo() from shape class')

class circle(shape):

def __init__(self, r):

print('call __init__ from circle class')

self.r = r

def calculate_area_circle(self):

return math.pi * self.r * self.r

class rectangle(shape):

def __init__(self, l, w):

print('call __init__ from rectangle class')

self.l = l

self.w = w

def calculate_area_rectangle(self):

return self.l * self.w

a = shape()

a.foo()

b = circle(5)

b.foo()

area = b.calculate_area_circle()

print('area:', area)

c = rectangle(2, 3)

c.foo()

area = c.calculate_area_rectangle()

print('area:', area)

Save these scripts into a file, called ch05_02.py.

Now run this file.

$ python3 ch05_02.py

Program output:

p5-2

5.7 Overriding Methods

We can override class methods in OOP. For instance, we have a class, shape, which has calculate_area(). We override this method from derived class by our own implementation.

Write these scripts for sample.

import math

class shape:

def __init__(self):

print('call __init__ from shape class')

def calculate_area(self):

print('calling calculate_area() from shape class')

return 0

class circle(shape):

def __init__(self, r):

print('call __init__ from circle class')

self.r = r

def calculate_area(self):

print('calling calculate_area() from circle class')

return math.pi * self.r * self.r

class rectangle(shape):

def __init__(self, l, w):

print('call __init__ from rectangle class')

self.l = l

self.w = w

def calculate_area(self):

print('calling calculate_area() from rectangle class')

return self.l * self.w

a = shape()

area = a.calculate_area()

print('area:', area)

b = circle(5)

area = b.calculate_area()

print('area:', area)

c = rectangle(2, 3)

area = c.calculate_area()

print('area:', area)

Save and run the program.

$ python3 ch05_03.py

A sample of program output:

p5-3

5.8 Overloading Operators

We can define our overloading operators in Python using __add__() for instance.

For completed, write these scripts.

class Point:

def __init__(self, x, y):

self.x = x

self.y = y

def __add__(self, other):

return Point(self.x + other.x, self.y + other.y)

def __sub__(self, other):

return Point(self.x - other.x, self.y - other.y)

def __mul__(self, other):

return Point(self.x * other.x, self.y * other.y)

def __str__(self):

return 'x' + str(self.x) + ', y:' + str(self.y)

a = Point(10, 3)

b = Point(2, 7)

c = Point(8, 1)

print(a)

print(a + b)

print(c - b)

print(a * c)

Save these scripts into a file, called ch05_04.py.

$ python3 ch05_04.py

A program output:

p5-4