Sunday, February 1, 2015

Week 4 Classes and subclasses

Week 4
Classes and Subclasses



Computer Science 148 has proved to be a really interesting course so far. Classes and subclasses are a fascinating area of study. However, there is a few points that cause trouble when trying to fully understand how Python works in terms of classes. I would like to tackle some of them here.


Let’s consider the following Python code for which we will assume we have dealt with the __str__ and __eq__ methods:




class FatherPower:
            ’’’A superclass that calculates the power of a number’’’

            def __init__(self):
                        ’’’Initialize a FatherPower class’’’
                        self.result = 0             

            def calculate_power(self, num):
                        ’’’ (int) -> int
Method that calculates the power of a number num
>>> son_class = FatherPower()
>>> son_class.calculate_power(3)
9
’’’
raise NotImplementedError(’need subclass’)
                       
class SonSquare(FatherPower):
’’’ A subclass that calculates the square of a number ’’’

def __init__(self):
                        ’’’Initialize a SonSquare subclass’’’
            FatherPower.__init__(self)

def calculate_power(self, num):
                        ’’’ (int) -> int
Method that calculates the square of a number num
>>> son_class = FatherPower()
>>> son_class.calculate_power(3)
9
’’’
# Sum of the numbers whose squares we calculated within the same instance of SonSquare
self.result = self.result + num
return num ** 2

There is a few things to look at.
1)      First, we notice that SonSquare inherits everything from the supperclass FatherPower. We make it explicit by calling the __init__ method of the supperclass (FatherPower.__init__(self)) and by doing so inheriting the variable self.result that we initialized in the supper class.

2)      Another thing to notice is that the method calculate_power is implemented in the subclass; therefore if we try to call the method directly from the supper classs, we will get a not implemented error.

3)      Super classes and subclasses have slightly different syntax.
Supper class: We write the word class followed by the name of the super class using the CamelCase. We do not include parenthesis after the name of the class.
Syntax: class FatherPower:
Subclass: We write the word class followed by the name of the subclass using the CamelCase. This time, we include the name of the superclass that our subclass inherits from between parentheses.
Syntax: class SonSquare(FatherPower):


I really enjoyed the material taught these weeks and I look forward to programming more on Python.

No comments:

Post a Comment