Class and Object(Instance)

Every objects includeing Integer or String are member(Instance) of Class. The behavior of the objects are identified by their Class. For example, + operator returns sum of numeric value (Integer of Float), also returns concatenated string if operands are string.
Class may have methods. As we saw before, String and List have many methods. Methods are functions that related to their Class.
Pythons's Class support Inheritance, when you make your own class, you can specify its perant class.

In a comparison of C++, the Class of Python is not so strict. Private data/method are not supported (but Mangling is possible by attaching __ before variable name). Data(attribute) which is not defined in Class can be added.

Class as a Data container

One of the usage of the class is a data container. Class instance can have attributes (variables). This usage is similar to struct of C/C++.


In [ ]:
# empty class for data container
class Test_case():
    pass

def distance(tc):
    '''
    tc: test_case instance
    return distance from (0,0) to (tc.x, tc,y)
    '''
    return (tc.x**2 + tc.y**2) ** (0.5)
    
    
tc1 = Test_case()  # create new instance
tc1.x = 100
tc1.y = 200

tc2 = Test_case()
tc2.x = 10
tc2.y = 30

print("tc1:", distance(tc1))
print("tc2:", distance(tc2))

Class variables and Instance variables

Each instance of the class can have its unique attributes (variables), as for above example, x and y are different value in tc1 and tc2. Class can have variables that belong to class (every instance refers same value). In order to use Class variables, use Class_name.variable_name

Object oriented

If class is designed properly, Program can be simpler and easier to understand (object oriented). The advantage of object oriented program is that it can bring higher level of abstraction.

abstract <-> specific $\fallingdotseq$ over all <-> detail


In [ ]:
class Beatles():
    def __init__(self, name):
        self.name = name
        self.best_friend = None
        
    def answer(self):
        print('My name is', self.name)
        
john = Beatles('John Lenon')
paul = Beatles('Paul McCartony')
george = Beatles('George Harrison')
ringo = Beatles('Ringo Starr')

print(john.name)
john.answer()  # perform answer methon on object john

john.best_friend = paul
paul.best_friend = george
george.best_friend = ringo
ringo.best_friend = john

print(john.best_friend.name)   # print john's best_friend name
print(john.best_friend.best_friend.name)  # john's best_friend = paul;  paul's best_friend name

john.best_friend.best_friend.best_friend.answer()

Special method of class

  • __init__(self, ...)
  • __lt__
  • __repr__
  • __add__
  • ...

In [ ]:
#!/usr/bin/python3
# -*- coding: utf-8 -*-

class rectangle():
    def __init__(self, size_x, size_y):
        self.size_x = size_x
        self.size_y = size_y
        self.area = size_x * size_y

    def __lt__(self, other):
        return self.area < other.area

    def __repr__(self):
        return ('Rectangle('+str(self.size_x)+'x'+str(self.size_y)+')')

sq1 = rectangle(1,11)
sq2 = rectangle(3,4)
sq3 = rectangle(2,5)

x = [sq1, sq2, sq3]
x.sort()
print(x)

Class usage sample (Binary Tree)


In [ ]:
# 2017 MMCPC rehearsal problem-D

class BinTreeNode():
    def __init__(self, val):
        self.val = val
        self.parent = None
        self.left = None
        self.right = None

    def add_left(self, left):
        left.parent = self
        self.left = left

    def add_right(self, right):
        right.parent = self
        self.right = right

    def add_child(self, child):
        if child.val < self.val:
            if self.left == None:
                self.add_left(child)
            else:
                self.left.add_child(child)
        else:
            if self.right == None:
                self.add_right(child)
            else:
                self.right.add_child(child)
                
                
    def print_node(self):
        if self.parent: print('Parent:', self.parent.val, end=' ')
        if self.left: print('Left:', self.left.val, end = ' ')
        if self.right: print('Right', self.right.val, end = ' ')
        print('Node val:', self.val)
        if self.left: self.left.print_node()
        if self.right: self.right.print_node()

In [ ]:
root_node = BinTreeNode(11)

for val in (6, 19, 4, 8, 17, 43, 5, 10, 31,49):
    node = BinTreeNode(val)
    root_node.add_child(node)
    
root_node.print_node()